8
2 3 8
1 7
1 4 5
3 5
3 4
7
2 6 8
1 7
1 2 7 6 8 3 4 5
def dfs(graph, v, visit):
res.append(v)
for g in graph[v]:
if not visit[g]:
visit[g] = True
dfs(graph, g, visit)
n = int(input())
graph = [[]]
for _ in range(n):
graph.append(list(map(int, input().split())))
res = []
visit = [False] * len(graph)
visit[1] = True
dfs(graph, 1, visit)
for r in res:
print(r, end=' ')
8
2 3 8
1 7
1 4 5
3 5
3 4
7
2 6 8
1 7
1 2 3 8 7 4 5 6
from collections import deque
def bfs(graph, start, visit):
queue = deque([start])
while queue:
v = queue.popleft()
res.append(v)
for g in graph[v]:
if not visit[g]:
visit[g] = True
queue.append(g)
n = int(input())
graph = [[]]
for _ in range(n):
graph.append(list(map(int, input().split())))
res = []
visit = [False] * len(graph)
visit[1] = True
bfs(graph, 1, visit)
for r in res:
print(r, end=' ')
4 5
00110
00011
11111
00000
3
def dfs(x, y):
if graph[x][y] == 1:
return False
graph[x][y] = 1
for step in steps:
nx = x + step[0]
ny = y + step[1]
if 0 <= nx <= n - 1 and 0 <= ny <= m - 1:
if graph[nx][ny] == 0:
dfs(nx, ny)
return True
n, m = map(int, input().split())
graph = []
for _ in range(n):
graph.append(list(map(int, input())))
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
res = 0
for i in range(n):
for j in range(m):
if dfs(i, j):
res += 1
print(res)
from collections import deque
def bfs(x, y):
if graph[x][y] == 1:
return False
queue = deque([(x, y)])
while queue:
x, y = queue.popleft()
for step in steps:
nx = x + step[0]
ny = y + step[1]
if 0 <= nx <= n - 1 and 0 <= ny <= m - 1:
if graph[nx][ny] == 0:
graph[nx][ny] = 1
queue.append((nx, ny))
return True
n, m = map(int, input().split())
graph = []
for _ in range(n):
graph.append(list(map(int, input())))
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
res = 0
for i in range(n):
for j in range(m):
if bfs(i, j):
res += 1
print(res)
5 6
101010
111111
000001
111111
111111
10
from collections import deque
def bfs(x, y):
queue = deque([(x, y)])
while queue:
x, y = queue.popleft()
for step in steps:
nx = x + step[0]
ny = y + step[1]
if 0 <= nx <= n - 1 and 0 <= ny <= m - 1:
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
queue.append((nx, ny))
n, m = map(int, input().split())
graph = []
for _ in range(n):
graph.append(list(map(int, input())))
steps = [(-1, 0), (1, 0), (0, -1), (0, 1)]
graph[0][0] = 1
bfs(0, 0)
print(graph[n - 1][m - 1])