[Algorithm] [๋ฐฑ์ค€] 1926 - ๊ทธ๋ฆผ (BFS) (Feat. ๐Ÿšซ)

myeonjiยท2022๋…„ 3์›” 7์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
67/89
post-custom-banner
  1. ์ž…๋ ฅ๋ฐ›์€ n, m์œผ๋กœ ์ด์ฐจ์›๋ฐฐ์—ด ๋งŒ๋“ ๋‹ค. ๊ทธ๋ž˜ํ”„ ํ•˜๋‚˜์”ฉ ๋Œ๋ฉด์„œ BFS ๋ฅผ ์‹คํ–‰ํ•œ๋‹ค.
  2. ์‹คํ–‰ํ•  ๋•Œ๋งˆ๋‹ค ํ•œ ์˜์—ญ์ด ์‹œ์ž‘๋˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ์ตœ์ข… ์˜์—ญ์ด ๋ช‡ ๊ฐœ์ธ์ง€ ๋‚˜ํƒ€๋‚ด๋Š” ๋ณ€์ˆ˜ count๋ฅผ +1 ํ•œ๋‹ค.
  3. BFS ์•ˆ์—์„œ๋Š” ํ•œ ์กฐ๊ฐ(?)๋งˆ๋‹ค cnt๋ฅผ +1 ํ•˜์—ฌ ํ•œ ์˜์—ญ ์•ˆ์— ์กฐ๊ฐ์ด ๋ช‡ ๊ฐœ ์žˆ๋Š”์ง€ ์„ผ๋‹ค.
  4. count์™€ ๊ฐ ์˜์—ญ์˜ cnt ์ค‘์— max๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

๐Ÿšซ ์š”์ฆ˜ ์ž์ฃผํ•˜๋Š” ์‹ค์ˆ˜,,

  • ๋ฐฉํ–ฅ ์ขŒํ‘œ ์“ฐ๊ณ  0 <= aa < n and 0 <= bb < m ์กฐ๊ฑด๋ฌธ ๋น ํŠธ๋ฆฌ์ง€ ๋ง๊ธฐ
  • graph ๋‚ด์— ๋ฐฉ๋ฌธ์ฒดํฌ ํ•˜๋ฉด ์•ˆ๋˜๊ณ  visited ๋ณ€์ˆ˜ ์จ์„œ ๋ฐฉ๋ฌธ์ฒดํฌ ํ•˜๊ธฐ
  • ๋ฐฉํ–ฅ์ฒดํฌ ์ขŒํ‘œ๋ฅผ ์จ์•ผํ•˜๋Š” ๋ฌธ์ œ์™€ ๊ทธ๋ ‡์ง€ ์•Š์€ ๋ฌธ์ œ ๊ตฌ๋ถ„ํ•˜๊ธฐ
## ๋ฐฑ์ค€ 1926 ๊ทธ๋ฆผ

import sys
input = sys.stdin.readline

# 1. ์ž…๋ ฅ๋ฐ›์€ n, m์œผ๋กœ ์ด์ฐจ์›๋ฐฐ์—ด ๋งŒ๋“ ๋‹ค. ๊ทธ๋ž˜ํ”„ ํ•˜๋‚˜์”ฉ ๋Œ๋ฉด์„œ BFS ๋ฅผ ์‹คํ–‰ํ•œ๋‹ค.
# 2. ์‹คํ–‰ํ•  ๋•Œ๋งˆ๋‹ค ํ•œ ์˜์—ญ์ด ์‹œ์ž‘๋˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ์ตœ์ข… ์˜์—ญ์ด ๋ช‡ ๊ฐœ์ธ์ง€ ๋‚˜ํƒ€๋‚ด๋Š” ๋ณ€์ˆ˜ count๋ฅผ +1 ํ•œ๋‹ค.
# 3. BFS ์•ˆ์—์„œ๋Š” ํ•œ ์กฐ๊ฐ(?)๋งˆ๋‹ค cnt๋ฅผ +1 ํ•˜์—ฌ ํ•œ ์˜์—ญ ์•ˆ์— ์กฐ๊ฐ์ด ๋ช‡ ๊ฐœ ์žˆ๋Š”์ง€ ์„ผ๋‹ค.
# 4. count์™€ ๊ฐ ์˜์—ญ์˜ cnt ์ค‘์— max๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

from collections import deque
def BFS(x, y):
    q = deque()
    cnt = 1
    q.append([x, y])
    visited[x][y] = 1

    while q:
        a, b = q.popleft()

        for i in range(4):
            aa = a + dx[i]
            bb = b + dy[i]
            if 0 <= aa < n and 0 <= bb < m and graph[aa][bb] == 1 and visited[aa][bb] == 0:
                visited[aa][bb] = 1
                q.append([aa, bb])
                cnt += 1  # 3
    return cnt


# 1
n, m = map(int, input().split())

graph = []
for _ in range(n):
    lst = list(map(int, input().split())) 
    graph.append(lst)

# ๋ฐฉํ–ฅ (์ขŒ์šฐ์ƒํ•˜)
dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]

count = 0
cnt_list = []
visited = [[0]*m for _ in range(n)]
for i in range(n):
    for j in range(m):
        if graph[i][j] == 1 and visited[i][j] == 0:
            cnt_list.append(BFS(i, j))  # 1
            count += 1  # ๊ทธ๋ฆผ์˜ ๊ฐœ์ˆ˜  # 2
 # 4
if count != 0:
    print(count)
    print(max(cnt_list))
else:
    print(count)
    print(0)
profile
DBA, ๊ฒฝ์ œ ๊ทธ๋ฆฌ๊ณ  ๊ณ ๋ƒฅ์ด
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€