I have a binary matrix (N*M) filled with 0 and 1. Example:
(S, 1, 1, 1, 0)
(1, 0, 0, 0, 1)
(1, 1, 0, 0, 1)
(1, 0, 1, 1, D)
The Startpoint S is the top-lefthand-corner and the Destination D is the buttom-righthand corner. Starting at S the following steps are allowed:
- 1 step down (↓)
- 1 step to the right (→)
- 1 diagonal step right and down(➘)
But only entries with a "1" may be used, as "0" represents an obstacle. So for instance in my example matrix there are three possible paths.
(S, 1, 1, 1, ) (S, , , , ) (S, , , , )
( , , , , 1) (1, , , , ) (1, , , , )
( , , , , 1) ( , 1, , , ) (1, 1, , , )
( , , , , D) ( , , 1, 1, D) ( , , 1, 1, D)
Goal: What I am looking for is the most efficient algorithm to determine whether or not there is a path. The algorithm only needs to output TRUE (if there exists at least one path from S to D) and FALSE (if there exists no path from S to D) under the above named restrictions. It does not need to determine the shortest path. Only whether or not a path fullfilling the criterias exist.
I have looked into DFS and BFS, but I am not sure whether these are the most efficient for my problem.
DFS and BFS would fit for this task. There is no more effective solution. You can't answer the question if you don't view the entire matrix, therefore the best algorithm should work for O(N*M). And DFS and BFS work for O(N*M).
The matrix is a graph which has N*M vertices. Each vertex has three or less neighbors.
You need to have an array [N, M] of boolean. When you visit a vertex [n, m], mark that you visited this one. And don't visit vertices which have already been visited.
Something like that: