在0和1的矩阵中查找路径

时间:2015-03-07 16:36:39

标签: python c algorithm matrix depth-first-search

最近我遇到了以下面试问题?

问题:您将获得一个包含M行和N列的二维矩阵。您最初位于(0,0),这是数组中的左上角单元格。您可以向右或向下移动。数组填充1和0。 1表示您可以在该单元格中移动,0表示您无法移动该单元格。返回从左上角单元格到右下角单元格的路径数(即(0,0)到(M-1,N-1))。由于答案可能很大,因此您必须返回ans%(10 ^ 9 + 7)。

任何人都可以告诉我如何处理或任何可能有帮助的算法吗?

修改

I have an approach 
1.Start with the top-left cell,initialize count=0
do 
2.Check if 1 exists in adjacent right or adjacent down cell.
3.Add the tuple (i,j) in the stack and choose the right path.
4.If we reach the bottom right cell , update count and pop from stack and go to that position (i,j).
while(stack is not empty)
5.Print count

我想知道是否有其他方法?

2 个答案:

答案 0 :(得分:2)

您可以将问题建模为Directed Acyclic Graph (DAG),然后查找从顶点s到顶点t的路径数量,这在DAG中很容易使用{ {3}}

在这里,将使用以下伪代码完成:

D(0,0) = 1 
D(x,y) = 0                      if x < 0
D(x,y) = 0                      if  y < 0
D(x,y) = 0                      if matrix[x][y] = 0
         D(x,y-1) + D(x-1,y)    Otherwise

通过在上面应用动态规划方法,您将得到一个矩阵,其中D(x,y)表示从(0,0)(x,y)的路径数,您的解决方案是{{1} }。

此解决方案的时间复杂度为D(n,m)


实现这个解决方案留给你,因为在理解它是如何完成之后它应该相当容易。

答案 1 :(得分:1)

伙计们经过我所有的努力终于我提交了我的代码,这将从(0,0)开始在矩阵中打印路径位置。

#!/usr/bin/env python

rows, cols = 0, 0
def traverse_matrix(A, directions, i, j, visited):
    global rows, cols
    def can_we_proceed(A, row, col, visited, current):
        return (row >=0 and row < rows and col >=0 and col < cols and \
                not visited[row][col] and (current == A[row][col]) and A[row][col] == 1)

    visited[i][j] = True
    for k in range(len(directions)):
        if can_we_proceed(A, i+directions[k][0], j+directions[k][1], visited, A[i][j]):
            print "({0},{1})".format(i+directions[k][0],j+directions[k][1])
            traverse_matrix(A, directions, i+directions[k][0], j+directions[k][1], visited)

def mysolution(a):
    global rows, cols
    rows, cols = len(a) , len(a[0])
    if (rows == 1 or cols == 1):
        return 1
    directions = [[1, 0], [0, -1], [-1, 0], [0, 1]]
    visited = []
    for i in range(rows):
        l = []
    for j in range(cols):
        l.append(False)
    visited.append(l)

    # tup1 = ();
    for i in range(rows):
        for j in range(cols):
            # tup1 = (i,j);
            if not visited[i][j]:
                traverse_matrix(A, directions, i, j, visited)   
                # print "Traversed {0};".format(tup1)
相关问题