牛客華為機試HJ43
阿新 • • 發佈:2022-04-20
1. 問題描述
2. Solution
1、思路
DFS
2、實現
import sys if sys.platform != "linux": file_in = open("input/HJ43.txt") sys.stdin = file_in def walk(i, j, pos=None): if pos is None: pos = [(0, 0)] if j + 1 < n and maze[i][j + 1] == 0 and (i, j + 1) not in pos: # 向右 walk(i, j + 1, pos + [(i, j + 1)]) if j - 1 >= 0 and maze[i][j - 1] == 0 and (i, j - 1) not in pos: # 向左 walk(i, j - 1, pos + [(i, j - 1)]) if i + 1 < m and maze[i + 1][j] == 0 and (i + 1, j) not in pos: # 向下 walk(i + 1, j, pos + [(i + 1, j)]) if i - 1 >= 0 and maze[i - 1][j] == 0 and (i - 1, j) not in pos: # 向上 walk(i - 1, j, pos + [(i - 1, j)]) if (i, j) == (m - 1, n - 1): # 到達出口 for x, y in pos: print(f'({x},{y})') while True: try: m, n = list(map(int, input().strip().split())) maze = [] for _ in range(m): maze.append(list(map(int, input().strip().split()))) walk(0, 0) except: break