top of page
Search

Day 6 | Lights Out | C++

  • Writer: Ayush Mahajan
    Ayush Mahajan
  • Aug 28, 2022
  • 2 min read

Another day, another step in learning about competitive programming. Today we will be solving Lights Out - https://codeforces.com/contest/275/problem/A… Don't forget to try it yourself.


This question has given instructions on what to do if a switch is toggled. We have to toggle the light and 4 lights adjacent (up, down, left, right).


Notice that if we toggle it even times, the result is nulled, and no matter how many odd times we toggled it, the result will be the same as if we toggled it 1 time.


So if a cell is toggled odd times, we toggle the following - (i,j) - cell itself (i-1,j) - cell above it (i+1,j) - cell below it (i,j+1) - cell to the right (i,j-1) - cell to the left


You can implement the above like this: https://codeforces.com/contest/275/submission/169494636… But this implementation is writing a lot of boilerplate code, you can actually save a lot of time in the contest by following the next implementation.


You might have noticed many competitive programmers have templates so they don't have to repeat themselves in the contest. One of the most common things you can find is this dx[] = {-1,1,0,0}, dy[] = {0,0,1,-1} (Order don't matter). Let me explain what is this.


The above 4 adjacent cells can be written like this as well (i-1,j-0) - cell above it (i+1,j-0) - cell below it (i-0,j+1) - cell to the right (i-0,j-1) - cell to the left


(i+dx[0],j+dy[0]) - cell above it (i+dx[1],j+dy[1]) - cell below it (i+dx[2],j+dy[2]) - cell to the right (i+dx[3],j+dy[3]) - cell to the left Thus we can use a loop instead of writing and rewriting a lot of code that has a high chance of having errors due to a typo.


You can implement the following like this: https://codeforces.com/contest/275/submission/169495181…


Notice: 1. I toggled using an XOR switch (https://geeksforgeeks.org/bitwise-operators-in-c-cpp/…) 2. I started with all lights as 0, then in end displayed toggled version, in the end, to speed up coding, which is a common practice in contests.

 
 
 

Comments


bottom of page