回答編集履歴
3
path と visited は同じなので、path を削除
test
CHANGED
@@ -84,11 +84,11 @@
|
|
84
84
|
|
85
85
|
|
86
86
|
|
87
|
-
def dfs(start, visited
|
87
|
+
def dfs(start, visited):
|
88
88
|
|
89
89
|
if len(visited) == n:
|
90
90
|
|
91
|
-
ans.append(
|
91
|
+
ans.append(visited)
|
92
92
|
|
93
93
|
else:
|
94
94
|
|
@@ -96,7 +96,7 @@
|
|
96
96
|
|
97
97
|
if c not in visited:
|
98
98
|
|
99
|
-
dfs(c, visited + [c]
|
99
|
+
dfs(c, visited + [c])
|
100
100
|
|
101
101
|
|
102
102
|
|
@@ -118,7 +118,7 @@
|
|
118
118
|
|
119
119
|
ans = []
|
120
120
|
|
121
|
-
dfs(1, [1]
|
121
|
+
dfs(1, [1])
|
122
122
|
|
123
123
|
print(len(ans))
|
124
124
|
|
2
説明の修正
test
CHANGED
@@ -20,7 +20,7 @@
|
|
20
20
|
|
21
21
|
3 4
|
22
22
|
|
23
|
-
この場合、[1, 2,
|
23
|
+
この場合、[1, 2, 4, 3] または [1, 3, 4, 2] の 2通りになるはずなのに、
|
24
24
|
|
25
25
|
質問のコードではそうなりません。
|
26
26
|
|
1
パスを表示するコードを追加
test
CHANGED
@@ -73,3 +73,55 @@
|
|
73
73
|
print(len(ans))
|
74
74
|
|
75
75
|
```
|
76
|
+
|
77
|
+
**追記**
|
78
|
+
|
79
|
+
次のようにすると、見つかったすべてのパスを表示できます。
|
80
|
+
|
81
|
+
```Python
|
82
|
+
|
83
|
+
from collections import defaultdict
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
def dfs(start, visited, path):
|
88
|
+
|
89
|
+
if len(visited) == n:
|
90
|
+
|
91
|
+
ans.append(path)
|
92
|
+
|
93
|
+
else:
|
94
|
+
|
95
|
+
for c in graph[start]:
|
96
|
+
|
97
|
+
if c not in visited:
|
98
|
+
|
99
|
+
dfs(c, visited + [c], path + [c])
|
100
|
+
|
101
|
+
|
102
|
+
|
103
|
+
n, m = map(int, input().split())
|
104
|
+
|
105
|
+
tree = defaultdict(list)
|
106
|
+
|
107
|
+
for _ in range(m):
|
108
|
+
|
109
|
+
a, b = map(int, input().split())
|
110
|
+
|
111
|
+
tree[a].append(b)
|
112
|
+
|
113
|
+
tree[b].append(a)
|
114
|
+
|
115
|
+
|
116
|
+
|
117
|
+
graph = dict(tree)
|
118
|
+
|
119
|
+
ans = []
|
120
|
+
|
121
|
+
dfs(1, [1], [1])
|
122
|
+
|
123
|
+
print(len(ans))
|
124
|
+
|
125
|
+
print(ans)
|
126
|
+
|
127
|
+
```
|