ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

๐Ÿšฉ ๊ทธ๋ž˜ํ”„์ด๋ก , ๊ทธ๋ž˜ํ”„ํƒ์ƒ‰, DFS, BFS

 

thinking

์ƒํ•˜์ขŒ์šฐ ๋‹ค ํƒ์ƒ‰ํ•˜๋ฉด์„œ ๋ฐฉ๋ฌธํƒ์ƒ‰ํ•˜๊ณ  ๊ฐ’์ด 1์ด๋ฉด(==๋ฐฐ์ถ”๋ฉด) ์นด์šดํŒ… 1 ์ฆ๊ฐ€

โญ ์ฒ˜์Œ์— ๊ทธ๋ƒฅ ํ’€์—ˆ๋”๋‹ˆ ๋Ÿฐํƒ€์ž„์—๋Ÿฌ๊ฐ€ ๋‚ฌ๋‹ค.

๊ตฌ๊ธ€๋ง ํ–ˆ๋”๋‹ˆ ์žฌ๊ท€ limit์„ ์„ค์ •ํ•ด์ฃผ์ง€ ์•Š์•„์„œ ๋ฐœ์ƒํ•œ ๋ฌธ์ œ๋ผ๊ณ  ํ•œ๋‹ค.

K(1 ≤ K ≤ 2500)์˜ ๋ฒ”์œ„๊ฐ€ ์—„์ฒญ ์ปค์„œ ๊ทธ๋Ÿฐ๋“ฏ?

ํŒŒ์ด์ฌ์˜ ๊ธฐ๋ณธ ์žฌ๊ท€ ํ•œ๋„๊ฐ€ (1000)์ด์–ด์„œ ์žฌ๊ท€ ๊นŠ์ด๊ฐ€ 1000์„ ๋„˜์–ด๊ฐˆ ๊ฒฝ์šฐ ๋ชจ๋“ˆ์„ ์ถ”๊ฐ€ํ•ด์ค˜์•ผํ•œ๋‹ค.


ํŒŒ์ด์ฌ ์ตœ๋Œ€ ์žฌ๊ท€ ๊นŠ์ด ๋Š˜๋ฆฌ๋Š” ๋ชจ๋“ˆ

import sys 
sys.setrecursionlimit(ํƒ์ƒ‰ํ•˜๊ณ ์žํ•˜๋Š” ๊นŠ์ด)

 

 

์ฝ”๋“œ

import sys
sys.setrecursionlimit(10000)

def dfs(r,c):
    dr = [0, 1, 0, -1]
    dc = [1, 0, -1, 0]
    a[r][c] = -1  # ๋ฐฉ๋ฌธ์ฒดํฌ
    for d in range(4):
        nr = r + dr[d]
        nc = c + dc[d]
        if nr < 0 or nr >= N or nc < 0 or nc >= M:  # ๋ฒ”์œ„์ฒดํฌ
            continue
        if a[nr][nc] == 1:
            a[nr][nc] = -1  # ๋ฐฉ๋ฌธ์ฒดํฌ
            dfs(nr,nc)

T = int(input())
for tc in range(1, T+1):
    M, N, K = map(int, input().split())  # M:๊ฐ€๋กœ๊ธธ์ด(์—ด ๊ธธ์ด), N:์„ธ๋กœ๊ธธ์ด(ํ–‰ ๊ธธ์ด), K:๋ฐฐ์ถ”๊ฐœ์ˆ˜
    a = [[0] * M for _ in range(N)]  # ๋ฐฐ์ถ”๋ฐญ

    for _ in range(K):  # ๋ฐฐ์ถ” 1๋กœ ๋ฐ”๊พธ๊ธฐ
        c, r = map(int, input().split())
        a[r][c] = 1

    cnt = 0
    for i in range(N):
        for j in range(M):
            if a[i][j] == 1:  # ๋ฐฐ์ถ”๋ฉด ์นด์šดํŠธ+1 & ๋ฐฉํ–ฅ ํƒ์ƒ‰
                dfs(i,j)
                cnt += 1

    print(cnt)

 

 

ํ•œ์ค„ํ›„๊ธฐ

๋ฐฑ์ค€์€ ๋Ÿฐํƒ€์ž„์—๋Ÿฌ๊ฐ€ ๋œจ๋ฉด ๋ญ๋•Œ๋ฌธ์— ๋œฌ ๊ฑด์ง€ ์•Œ๋ ค์คฌ์Œ ์ข‹๊ฒ ๋‹ค

๋Œ“๊ธ€