在矩阵中从左上角到底部的所有路径打印所有1s的路径

发布于 2025-02-11 04:16:23 字数 860 浏览 1 评论 0原文

您给出了一个带有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文