在矩阵中查找X的路径

时间:2015-06-01 17:27:42

标签: algorithm matrix path

给定一个n×n矩阵作为输入我们必须找到1s的路径是否存在(0,0)到X(矩阵的中间)。输入是

1 1 1 0 0
1 0 0 0 0 
1 0 X 1 1
1 0 0 0 1
1 1 1 1 1

输出应为true,因为我们有这条路径

1
1
1   X 1 1
1       1
1 1 1 1 1

有人可以解释一下更好的方法吗。谢谢。这是我的算法:

输入矩阵是A,其中X由任何正数表示 访问矩阵[n] [n]初始化为零 intially flag = 0; 调用find(0,0,& flag),然后检查flag = 1是否存在路径。

void find(int i,int j,int * flag)
{

    visited[i][j]=1;

    if(i==n/2)and(j==n/2)
    {
    *flag=1;
     return
    }

    if(A[i+1][j]>0)and(visited[i+1]==0)and(i+1<n)
    find(i+1,j,flag);

    if(A[i-1][j]>0)and(visited[i-1]==0)and(i-1>0)
    find(i-1,j,flag);

    if(A[i][j+1]>0)and(visited[j+1]==0)and(j+1<n)
    find(i,j+1,flag);

    if(A[i][j-1]>0)and(visited[j-1]==0)and(j-1>0)
    find(i,j-1,flag);
}

1 个答案:

答案 0 :(得分:1)

您的递归算法可能是DFS,它不会保留visited集,因此会多次重新展开节点。

可以通过添加和维护visited集来解决,如果某个节点在集合中,则跳过它并且不重新展开它。

更好的选择是使用BFS而不是DFS。如果你想在以后找到路径,BFS也会保持visited集(或parent集),并且还可以保证找到从源到目标的最短路径。

BFS的Pesudo代码:

q = new empty queue
parent = {} //new empty dictionary
q.enqueue((0,0))
parent[(0,0)] = null
while q is not empty:
    current = q.dequeue()
    if current is the target x:
         return findPath(parent, current)
    for each neighbor n of current:
       if n is a key in parent:
          continue
       q.add(n)
       parent[n] = current

findPath(parent, target):
    l = new list
    while (target != null):
       l.add(target)
       target = parent[target]