Search code examples
algorithmmatrixcycle

Determine a cycle in a matrix


I have a matrix and each cell has a boolean property. I need to determine a cycle, starting from a cell that has the boolean property false, and this cycle must contain only cells that have that boolean property set to true (except the starting cell, obviously). Another condition is that any two consecutive cells in the cycle must be on the same row (or on the same column), and that three consecutive cells in the cycle must not be on the same row (or on the same column). You can actually jump from one cell to another, they don't have to be neighbours, they just have to be on the same row or column. Thank you.


Solution

  • Update: I missed that a move is not required to be between two adjacent cells - this enlarges the number of possible moves at each step but does not really change the general idea.

    The easiest implementation is probably depth-first search - you start at the starting cell and look at all possible moves - except for the first move there are at most three possible moves. For each possible move you do the same recursively until you reach the starting cell again or there is no possible move remaining. In the later case you track back one move and try the next possibility if there is one remaining.

    You have to pass the direction of the last move along with the recursive call because this direction is not valid for the next move. If it is not allowed to visit cells several times you have to track the visited cells, too, and unmark them when tracking back. If it is allowed to visit cells several times you have to track the direction you left a cell when you visited it before in order to avoid cycles.

    Using breath-first search instead of depth-first search will avoid trying long paths that are no solutions at the cost of keeping book of a large number of partial solutions. A* search might be another option to speed this up.

    Side note: It may be the case that there is no value in visiting a cell several times because you could have take the other move directly when visiting the cell for the first time. The exception is doing the move not allowed when entering the cell for the first time but I am not sure if such a path is possible.