โ๏ธ ๋ฌธ์
๐ถ๏ธ ํด์ค
โ๏ธ ์ ๋ ฅ
def dfs(x, y):
if x < 0 or y < 0 or x >= N or y >= M:
return False
if grahp[x][y] == 0:
grahp[x][y] = 1
dfs(x - 1, y)
dfs(x, y - 1)
dfs(x + 1, y)
dfs(x, y + 1)
return True
return False
N, M = map(int, input().split())
result = 0
grahp = []
for i in range(N):
grahp.append(list(map(int, input())))
print(grahp)
for i in range(N):
for j in range(M):
if dfs(i, j) == True:
result += 1
print(result)
๐ป ์ถ๋ ฅ
> 4 5
00110
00011
11111
00000
3
โ๏ธ ๋ฌธ์
๐ถ๏ธ ํด์ค
โ๏ธ ์ ๋ ฅ
from collections import deque
n, m = map(int,input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(x, y):
queue = deque()
queue.append((x, y))
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or ny < 0 or nx >= n or ny >= m:
continue
if graph[nx][ny] == 0:
continue
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
queue.append((nx, ny))
return graph[n - 1][m - 1]
print(bfs(0,0))
๐ป ์ถ๋ ฅ
>3 3
110
010
011
5
[์ถ์ฒ] ์ด๊ฒ์ด ์ทจ์ ์ ์ํ ์ฝ๋ฉํ ์คํธ๋ค. with python (๋๋๋น ์ง์)