๋ฐ์ํ
๐ค๋ฌธ์ ํด๊ฒฐ
-
S2 | ๊ทธ๋ํ, DFS
๋ฐฐ์ถ๋ฐญ๊ณผ ๋ฐฐ์ถ์ ์์น๋ฅผ 2์ฐจ์๋ฐฐ์ด๋ก ๋ง๋ ๋ค.
๋ฐฐ์ถ๋ฆฌ์คํธ์์ ํ๋ ๊บผ๋ด์ DFS๋ก ์ธ์ ํ ๋ฐฐ์ถ๋ค์ ๋ค 0์ผ๋ก ๋ฐ๊ฟ์ค๋ค.
๐ป์์ค ์ฝ๋
import sys
input = sys.stdin.readline
def find_dummy(x: int, y: int):
farm[x][y] = 0
stack = [(x, y)]
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
while stack:
cx, cy = stack.pop()
for k in range(len(dx)):
nx = cx + dx[k]
ny = cy + dy[k]
if 0 <= nx < N and 0 <= ny < M and farm[nx][ny] == 1:
stack.append((nx, ny))
farm[nx][ny] = 0
if __name__ == '__main__':
print()
for _ in range(int(input())): # ํ
์คํธ์ผ์ด์ค ๊ฐ์
M, N, K = map(int, input().split()) # ๊ฐ๋ก, ์ธ๋ก, ๋ฐฐ์ถ ๊ฐ์
farm = [[0] * M for _ in range(N)]
cabbages = [] # ๋ฐฐ์ถ๋ฆฌ์คํธ
for _ in range(K):
X, Y = map(int, input().split())
farm[Y][X] = 1 # ๋ฐฐ์ถ ์ฌ๊ธฐ
cabbages.append((Y, X))
answer = 0
for cabbage in cabbages:
if farm[cabbage[0]][cabbage[1]] == 1: # ๋ฐฐ์ถ๊ฐ ์ฌ์ด์ ธ์์ผ๋ฉด
find_dummy(cabbage[0], cabbage[1]) # ๊ทธ ๋ฐฐ์ถ์ ์ฃผ๋ณ ๋ฐฐ์ถ 0์ผ๋ก ๋ง๋ค๊ธฐ
answer += 1 # ๋๋ฏธ์ ๊ฐ์ ์ถ๊ฐ
print(answer)
๐๋ฌธ์ ํ์ธ
์ถ์ฒ: BACKJOON ONLINE JUDGE
๋ฐ์ํ
'Algorithm Problem > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[python] SWEA - 10912. ์ธ๋ก์ด ๋ฌธ์ (0) | 2020.11.02 |
---|---|
[python] SWEA - 10804. ๋ฌธ์์ด์ ๊ฑฐ์ธ์ (0) | 2020.11.01 |
[python] ๋ฐฑ์ค - 14719. ๋น๋ฌผ (0) | 2020.10.30 |
[python] ๋ฐฑ์ค - 12865. ํ๋ฒํ ๋ฐฐ๋ญ (0) | 2020.10.29 |
[python] ๋ฐฑ์ค - 1325. ํจ์จ์ ์ธ ํดํน (0) | 2020.10.28 |