์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œํ’€์ด

[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์ˆœ์œผ๋กœ ์ด๋ฃจ์–ด์ง„๋‹ค.

์ด๋ฏธ์ง€ ์ถœ์ฒ˜:&nbsp;https://wikidocs.net/80519