728x90
๐ ๋ฐฑ์ค 4963 - ์ฌ์ ๊ฐ์
๐ก ๋์ ํ์ด
BFS
ํน์ DFS
๋ง ์ ๊ตฌํํ ์ ์๋ค๋ฉด ์ด๋ ค์ด ๋ฌธ์ ๋ ์๋๋ค. ๋ค๋ง, ๊ธฐ์กด ๋ฌธ์ ์์๋ ์, ํ, ์ข, ์ฐ ํจํด์ด ๋ฑ์ฅํ๋ค๋ฉด ์ด๋ฒ์๋ ๋๊ฐ์ ํจํด์ด ๋ฑ์ฅํ๋ค. ์ด์ ๋ฑ์ฅํ์ผ๋ ๋ค์ ์ธ ๊ฐ์ง ํจํด์ ์์๋ณด์.
728x90
- ์, ํ, ์ข, ์ฐ ํจํด
dx = [1, 0, -1, 0] dy = [0, 1, 0, -1]
- ๋๊ฐ์ + ์, ํ, ์ข, ์ฐ ํจํด
dx = [-1, -1, -1, 0, 0, 1, 1, 1] dy = [-1, 0, 1, -1, 1, -1, 0, 1]
- ๋๊ฐ์ ํจํด
dx = [-1, -1, 1, 1] dy = [-1, 1, -1, 1]
ํจํด2๋ฅผ ์ฌ์ฉํ๋ฉด ์ฝ๊ฒ ํด๊ฒฐํ ์ ์๋ค. ๊ทธ๋ฆฌ๊ณ while
๋ฌธ ์ข
๋ฃ์กฐ๊ฑด์ ์
๋ ฅ์ด 0, 0
์ด์ด์ผ ํ๋๋ฐ, ์ด๋ if not w and not h
์กฐ๊ฑด์ ์ฃผ๋ฉด ์ฝ๊ฒ ํด๊ฒฐํ ์ ์๋ค.
from collections import deque def bfs(x, y): queue = deque() queue.append((x, y)) visited[x][y] = True while queue: x, y = queue.popleft() for i in range(8): nx = x + dx[i] ny = y + dy[i] if 0 <= nx < h and 0 <= ny < w: if graph[nx][ny] == 1 and not visited[nx][ny]: visited[nx][ny] = True queue.append((nx, ny)) dx = [-1, -1, -1, 0, 0, 1, 1, 1] dy = [-1, 0, 1, -1, 1, -1, 0, 1] while True: w, h = map(int, input().split()) if not w and not h: break graph = [list(map(int, input().split())) for _ in range(h)] visited = [[False] * w for _ in range(h)] cnt = 0 for i in range(h): for j in range(w): if graph[i][j] == 1 and not visited[i][j]: bfs(i, j) cnt += 1 print(cnt)
๋ฐ์ํ
'Algorithm > ๋ฐฑ์ค(BOJ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ ํ์ด์ฌ(python) ] ๋ฐฑ์ค 1303 - ์ ์ - ์ ํฌ(BFS) (3) | 2021.04.21 |
---|---|
[ ํ์ด์ฌ(python) ] ๋ฐฑ์ค 4963 - ์ฌ์ ๊ฐ์(DFS) (0) | 2021.04.20 |
[ ํ์ด์ฌ(python) ] ๋ฐฑ์ค 7576 - ํ ๋งํ (BFS) (0) | 2021.04.20 |
[ ํ์ด์ฌ(python) ] ๋ฐฑ์ค 1926 - ๊ทธ๋ฆผ(BFS) (0) | 2021.04.20 |
[ ํ์ด์ฌ(python) ] ๋ฐฑ์ค 2606 - ๋ฐ์ด๋ฌ์ค(DFS) (0) | 2021.04.19 |
๋๊ธ