Existence of path in binary matrix with specified directions

324 views Asked by At

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. 1 step down (↓)
  2. 1 step to the right (→)
  3. 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.

1

There are 1 answers

0
Dantesto On BEST ANSWER

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:

global int N, M
global int S = 2, D = 3 --assuming that start in matrix marked as 2 and destination as 3
global int matrix[N, M]
global bool visited[N, M] --initially filled with False

bool DFS(n, m)
    if n >= N || m >= M || visited[n, m] || matrix[n, m] == 0 then
        return False
    visited[n, m] = True
    return matrix[n, m] == D || DFS(n + 1, m) || DFS(n, m + 1) || DFS(n + 1, m + 1)

print(DFS(0, 0))