文章目录
卡码网98.所有可达路径
深度优先某种程度上和回溯真的一模一样,先进行终止条件判断,然后进入当前结点的遍历,满足条件进行操作后进入下一步的递归,最后回溯。
python
ans = []
def dfs(root, Nodes, pre, target):
if root == target:
ans.append(pre[:])
return
for j in range(1, target+1):
if Nodes[root-1][j-1]:
pre.append(j)
dfs(j, Nodes, pre, target)
pre.pop()
if __name__ == '__main__':
NM = input().split()
N, M = int(NM[0]), int(NM[1])
ss, ts = [], []
for i in range(M):
st = input().split()
s, t = int(st[0]), int(st[1])
ss.append(s)
ts.append(t)
Nodes = [[False] * N for _ in range(N)]
for i, j in zip(ss, ts):
Nodes[i-1][j-1] = True
dfs(1, Nodes, [1], N)
if len(ans) == 0:
print(-1)
else:
for result in ans:
print(' '.join(map(str, result)))