python
复制代码
def dfs(x, y, path, grid):
n = len(grid)
m = len(grid[0])
if x == n-1 and y == m-1:
for cor in path:
print("({},{})".format(cor[0],cor[1]))
# 判断条件:1不能越界 2不能撞墙 3走过的不能走
if 0 <= x+1 < n and 0 <= y < m and grid[x+1][y] != 1:
path.append((x+1, y))
grid[x+1][y] = 1
dfs(x+1, y, path, grid)
path.pop()
grid[x + 1][y] = 0
if 0 <= x-1 < n and 0 <= y < m and grid[x-1][y] != 1:
path.append((x-1, y))
grid[x-1][y] = 1
dfs(x-1, y, path, grid)
path.pop()
grid[x - 1][y] = 0
if 0 <= x < n and 0 <= y+1 < m and grid[x][y+1] != 1:
path.append((x, y+1))
grid[x][y+1] = 1
dfs(x, y+1, path, grid)
path.pop()
grid[x][y + 1] = 0
if 0 <= x < n and 0 <= y-1 < m and grid[x][y-1] != 1:
path.append((x, y-1))
grid[x][y-1] = 1
dfs(x, y-1, path, grid)
path.pop()
grid[x][y - 1] = 0
if __name__ == "__main__":
n, m = map(int, input().split())
grid = []
for _ in range(n):
grid.append(list(map(int, input().split())))
# print(grid)
path = [(0, 0)]
grid[0][0] = 1
dfs(0,0,path, grid)