๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/๋ฐฑ์ค€(BOJ)

[ ํŒŒ์ด์ฌ(python) ] ๋ฐฑ์ค€ 1926 - ๊ทธ๋ฆผ(BFS)

by YWTechIT 2021. 4. 20.
728x90

๐Ÿ“Œ ๋ฐฑ์ค€ 1926 - ๊ทธ๋ฆผ

๋ฌธ์ œ ์„ค๋ช…


๐Ÿ’ก ๋‚˜์˜ ํ’€์ด

BFS๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๋Š”๋ฐ, queue์— ์žˆ๋Š” ์›์†Œ๋ฅผ popํ•  ๋•Œ๋งˆ๋‹ค cnt+=1ํ•ด์ฃผ๋Š”๊ฒƒ์„ while๋ฌธ์— ์“ฐ์ง€ ์•Š๊ณ  ์—‰๋šฑํ•œ ๊ณณ์— ์ผ๋‹ค๊ฐ€ ๋‹ต์ด ์•ˆ ๋‚˜์™€์„œ ํ—ค๋งธ๋‹ค. ๋˜ ์ค‘์š”ํ•œ๊ฒƒ์€ ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋ ๋•Œ๋งˆ๋‹ค each_cnt๋ฅผ 1๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ฃผ์ž. ์•„๋‹ˆ๋ฉด ๊ฐ’์ด ๊ณ„์† ๋ˆ„์ ๋œ๋‹ค.

 

๊ทธ๋ฆฌ๊ณ  ์ตœ๋Œ€๊ฐ’์„ ๊ฐฑ์‹ ํ•ด์ค„ ๋•Œ ๊ตณ์ด ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋„ฃ์ง€ ์•Š์•„๋„ return each_cnt์„ ํ•ด์ฃผ๊ณ  ๋‚˜์˜ค๋Š” ๊ฐ’๊ณผ 0๋ถ€ํ„ฐ max๋กœ ๋น„๊ตํ•ด์ฃผ๋ฉด ๋‚˜์ค‘์— ์ œ์ผ ํฐ ๊ฐ’๋งŒ ๋นผ๋‚ผ ์ˆ˜ ์žˆ๋‹ค. ๊ฐ€์žฅ ๊ฐ„๋‹จํ•œ ๋น„๊ต๋ฐฉ๋ฒ•์ด๋‹ˆ ์™ธ์›Œ๋‘์ž.

728x90
  1. ์™ธ๋ถ€์—์„œ ๋ชจ๋“  ์ขŒํ‘œ๋ฅผ ํ•˜๋‚˜์”ฉ ๋„ฃ์„ ๋•Œ BFS๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์กฐ๊ฑด์ด ์ถฉ์กฑ๋˜๋ฉด cnt+=1 ํ•ด์ค€๋‹ค.
  2. BFS ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ ์›์†Œ๋ฅผ popํ• ๋•Œ each_cnt+=1์„ ํ•ด์ค€๋‹ค.
  3. return each_cnt์™€ ์ตœ์ดˆ 0์œผ๋กœ ์ •์˜ํ•œ max_each_count ์ค‘ ํฐ ๊ฐ’์œผ๋กœ ๊ฐฑ์‹ ํ•˜๋ฉด์„œ ๋ฐ˜๋ณต๋ฌธ์ด ๋๋‚˜๋ฉด ๊ฐ€์žฅ ๋†’์€ ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

import sys
from collections import deque
input = sys.stdin.readline

def bfs(x, y):
    each_cnt = 1    # init each_cnt
    queue = deque()
    queue.append((x, y))
    visited[x][y] = True

    while queue:
        x, y = queue.popleft()

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < n and 0 <= ny < m:
                if graph[nx][ny] == 1 and not visited[nx][ny]:
                    visited[nx][ny] = True
                    queue.append((nx, ny))
                    each_cnt += 1    # update each_cnt
    return each_cnt    # end each_cnt

n, m = map(int, input().split())
visited = [[False] * m for _ in range(n)]
graph = [list(map(int, input().split())) for _ in range(n)]

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

cnt, max_each_count = 0, 0
for i in range(n):
    for j in range(m):
        if graph[i][j] == 1 and not visited[i][j]:
            cnt += 1    # dfs work condition
            max_each_count = max(max_each_count, bfs(i, j))    # update max_each_count

print(cnt)
print(max_each_count)
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€