Idea
- Each column has at least 1 black, if all black through out, can return ‘YES’ straight
- Otherwise, we need to visit each column once to ensure each black grid can be visited
- The idea here is to find a starting point - the point here is only one black grid, so there is only one way to kickstart
- Since the starting point can be in the middle, so we need to have 2 loops, one is to the left, another one to the right. We need to make sure all black grids at all columns can be visited and not repeated
- When we move to a new column, we need to visit all the black in that column, and the first black must be adjacent to the previous one. If there are 2 black grids, and we only consider one is abit point, we need to come back to this column which is tough to program
- So we just make sure we visit all black grids in current columns, and the last grid is going to be our new starting point → optimal structure(if we past each column, then we obtain the answer) & statelessness(to visit the next grid, we just need to know what is our current starting point)
Space & time analysis
- Space - O(1), we are only using a few variables to deliver the answer
- Time - O(n), we need to array to find the starting point, then visit each column once to ensure we can visit all black grids.
Codes