๐Ÿ“Œ DFS & BFS ๊ธฐ์ดˆ ๋ฌธ์ œ ํ’€์ด (์ด๊ฒƒ์ด ์ทจ์—…์„ ์œ„ํ•œ ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋‹ค with python)

๋ชจ๊น…ยท2023๋…„ 3์›” 15์ผ
0

๐Ÿ“– 01. <๋ฌธ์ œ> ์Œ๋ฃŒ์ˆ˜ ์–ผ๋ ค ๋จน๊ธฐ

โœ๏ธ ๋ฌธ์ œ

๐Ÿ•ถ๏ธ ํ•ด์„ค

โœ๏ธ ์ž…๋ ฅ

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

๐Ÿ“– 02. <๋ฌธ์ œ> ๋ฏธ๋กœ ํƒˆ์ถœ

โœ๏ธ ๋ฌธ์ œ

๐Ÿ•ถ๏ธ ํ•ด์„ค

โœ๏ธ ์ž…๋ ฅ

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 (๋‚˜๋™๋นˆ ์ง€์Œ)

profile
๋ฉˆ์ถ”์ง€ ์•Š๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€