可达路径-98
python
def dfs(graph,cur,n,path,result):
if cur == n:
result.append(path.copy())
return
for i in range(n+1):
if graph[cur][i]:
path.append(i)
dfs(graph,i,n,path,result)
path.pop()
def main():
n,m = map(int,input().split())
# 节点编号从1开始,所以下标增加到n+1
graph = [[0] * (n+1) for _ in range(n+1)]
for _ in range(m):
i,o = map(int,input().split())
graph[i][o] = 1
result = [] # 二维数组,放全部的结果
path = [1] # 放的是单一路径
dfs(graph,1,n,path,result)
if not result:
print("-1")
else:
for path in result:
print(' '.join(map(str,path)))
if __name__ == '__main__':
main()