์๊ณ ๋ฆฌ์ฆ/๋ฌธ์ ํ์ด
[Python] ๋ฐฑ์ค 4963๋ฒ ์ฌ์ ๊ฐ์
์๋๋
2023. 2. 18. 23:08
| ๋ฌธ์ ๋ด์ฉ
2์ฐจ์ ๋ฐฐ์ด์์ 1๋ก ํ์๋ ์ฌ์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ . ์ํ์ข์ฐ์ ๋๊ฐ์ ๊น์ง ๊ณ ๋ คํด์ ์ฌ์ธ์ง ์ฒดํฌํด์ผํ๋ค.
| ํ์ด
ํ ์คํธ ๋ฐ์ดํฐ์ ๋ง๋ ์ง๋(matrix)๋ฅผ ์ค์ ํ๊ณ ๊ฐ์ด 1์ธ ์ง์ ์์ BFS๋ DFS๋ก ์ฃผ๋ณ๊ฐ์ด 1์ด๋ฉด ๊ฐ์ ์ฌ์ผ๋ก ์ธ์ํด๊ฐ๋ฉด์ ์ง๋ ๋ด ์ ์ฒด ์ฌ์ ๊ฐ์๋ฅผ ์ฒดํฌ
1) BFS ํ์ด
import sys
read = sys.stdin.readline
def bfs(queue):
# ๋๊ฐ์ ๋ฐฉํฅ ๊ณ ๋ ค
dx = [0, 1, 1, 1, 0, -1, -1, -1]
dy = [1, 1, 0, -1, -1, -1, 0, 1]
while queue:
x, y = queue.pop()
matrix[x][y] = 0
for d in range(8):
nx = x + dx[d]
ny = y + dy[d]
if (0 <= nx < h) and (0 <= ny < w):
if matrix[nx][ny] == 1 and (nx, ny) not in queue:
queue.append((nx, ny))
while True:
w, h = map(int, input().split())
if w == 0 and h == 0:
break
matrix = []
count = 0
for _ in range(h):
matrix.append(list(map(int, read().split())))
for x in range(h):
for y in range(w):
if matrix[x][y] == 1:
count += 1
bfs([(x, y)])
print(count)
2) DFS ํ์ด
import sys
read = sys.stdin.readline
sys.setrecursionlimit(10000) # ์์ฐ๋ฉด ๋ฐํ์์๋ฌ...
def dfs(x, y):
# ๋๊ฐ์ ๋ฐฉํฅ ๊ณ ๋ ค
dx = [0, 1, 1, 1, 0, -1, -1, -1]
dy = [1, 1, 0, -1, -1, -1, 0, 1]
matrix[x][y] = 0
for d in range(8):
nx = x + dx[d]
ny = y + dy[d]
if (0<= nx < h) and (0<= ny < w) and matrix[nx][ny] == 1:
dfs(nx, ny)
while True:
w, h = map(int, input().split())
if w == 0 and h == 0:
break
matrix = []
count = 0
for _ in range(h):
matrix.append(list(map(int, read().split())))
for x in range(h):
for y in range(w):
if matrix[x][y] == 1:
count += 1
dfs(x, y)
print(count)
| ๋๋์
ํ์คํ BFS๋ณด๋ค DFS๋ก ํ์์ ๋ ์๋๊ฐ ์ด์ง ๋(80ms) ๋น ๋ฅด๋ค.
๊ทธ๋ฆฌ๊ณ ํ์ด์ฌ ๊ณต๋ถ๋ฅผ ์ข ๋ ํด์ผ๊ฒ ๋ค ใ ใ ;
- input๋ณด๋ค๋ sys.stdin.readline์ด ๋ ๋น ๋ฅด๋ค
- ํ์ด์ฌ ๋ณ์ ์ฐธ์กฐ๋ LEGB์์ผ๋ก ์ด๋ฃจ์ด์ง๋ค.