在矩阵中从左上角到底部的所有路径打印所有1s的路径
您给出了一个带有M行的2-D矩阵和N列。您可以向右移动(r)或向下移动(d)。阵列充满了1和0。一个1表示您可以通过该单元格移动,a 0表示您不能通过该单元格移动。
将所有可能的路径从左上的单元格到右下右单元格。(即(0,0)到(M-1,N-1))。
输出可以像[[r,r,d,d],[r,d,d,r],[d,d,r,r]]
无法使用我在下面尝试的代码生成正确的输出:
def traverse(grid, rows, cols, i, j, result, path, element):
if i==rows-1 and j==cols-1:
result.append(path)
print(result)
path = []
return
if i>=rows or j>=cols or grid[i][j]==0:
path = []
return
if grid[i][j] == 1 and element != 'x':
path.append(element)
traverse(grid, rows, cols, i, j+1, result, path, 'r')
traverse(grid, rows, cols, i+1, j, result, path, 'd')
grid = [[1,1,1],[0,1,1],[1,1,1]]
rows = len(grid)
cols = len(grid[0])
traverse(grid, rows, cols, 0, 0, [], [], 'x')
You are given a 2-D matrix with M rows and N columns.You are initially positioned at (0,0) which is the top-left cell in the array. You are allowed to move either right (R) or downwards (D). The array is filled with 1’s and 0’s. A 1 indicates that you can move through that cell, a 0 indicates that you cannot move through that cell.
Print all possible paths from top-left cell to bottom-right cell.(i.e. (0,0)to(M-1,N-1)).
Output can be like [[R,R,D,D], [R,D,D,R], [D,D,R,R]]
Not able to generate correct output with the code I tried below:
def traverse(grid, rows, cols, i, j, result, path, element):
if i==rows-1 and j==cols-1:
result.append(path)
print(result)
path = []
return
if i>=rows or j>=cols or grid[i][j]==0:
path = []
return
if grid[i][j] == 1 and element != 'x':
path.append(element)
traverse(grid, rows, cols, i, j+1, result, path, 'r')
traverse(grid, rows, cols, i+1, j, result, path, 'd')
grid = [[1,1,1],[0,1,1],[1,1,1]]
rows = len(grid)
cols = len(grid[0])
traverse(grid, rows, cols, 0, 0, [], [], 'x')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论