Post

[BOJ] 10026. ์ ๋ก์ƒ‰์•ฝ(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ์ƒ‰๊น” ๊ตฌ๋ณ„ํ•˜๊ธฐ
    • ์ ๋ก์ƒ‰์•ฝ์ด ์žˆ๋Š” ์‚ฌ๋žŒ: ์ ์ƒ‰/๋…น์ƒ‰์ด๋ฉด ์ ์ƒ‰๊ณผ ๋…น์ƒ‰์ด ๊ฐ™์€ ์ƒ‰์ด๋ผ๊ณ  ํ™•์ธ
    • ์ƒ‰๋ก์ƒ‰์•ฝ์ด ์—†๋Š” ์‚ฌ๋žŒ: RGB๋ชจ๋‘ ๊ตฌ๋ณ„ํ•จ
  2. ๊ตฌ์—ญ ๊ตฌ๋ณ„ํ•˜๊ธฐ
    • ์ ๋ก์ƒ‰์•ฝ์ด ์žˆ๋Š” ์‚ฌ๋žŒ์€ ์ ์ƒ‰๊ณผ ๋…น์ƒ‰์„ ๊ฐ™์€ ์ƒ‰์ด๋ผ๊ณ  ๋ณด๊ธฐ๋•Œ๋ฌธ์— bfs์—์„œ ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๊ณณ์ผ ์ˆ˜๋„ ์žˆ๋‹ค.
    • ์ ๋ก์ƒ‰์•ฝ์ด ์—†๋Š” ์‚ฌ๋žŒ์€ ์ ์ƒ‰๊ณผ ๋…น์ƒ‰์„ ๊ตฌ๋ณ„ํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์–ด ๋”ฐ๋กœ ๋ฐฉ๋ฌธ์ฒดํฌ๋ฅผ ํ•ด์ค€๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import sys
from collections import deque
input = sys.stdin.readline

def chk(color,have,y,x):
    if have:
          if not visited_have[y][x]:
            if (color!='B' and grid[y][x]!='B') or (color=='B' and grid[y][x]=='B'): 
               visited_have[y][x]=True
               return True
    else:
       if not visited[y][x] and grid[y][x]==color: 
         visited[y][x]=True
         return True
    return False

def bfs(y,x,color,have):
   queue = deque()
   queue.append((y,x))

   while queue:
      ny,nx = queue.popleft()
      for i in range(4):
        ey,ex = ny + dy[i], nx + dx[i]
        if 0<=ey<n and 0<=ex<n:
           if chk(color,have,ey,ex):
               queue.append((ey,ex))

n = int(input())
grid = []
for _ in range(n):
   grid.append(input().rstrip())

dy = (-1,0,1,0)
dx = (0,1,0,-1)

visited_have = [[False for _ in range(n)]for _ in range(n)]
visited = [[False for _ in range(n)]for _ in range(n)]

answer=[0,0]
for i in range(n):
   for j in range(n):
      color = grid[i][j]

      if not visited[i][j]:
        visited[i][j]=True
        answer[0]+=1
        bfs(i,j,color,False)

      if not visited_have[i][j]:
         visited_have[i][j]=True
         answer[1]+=1
         bfs(i,j,color,True)
print(answer[0],answer[1])
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.