[BOJ] 10026. ์ ๋ก์์ฝ(python)
๐๋ฌธ์
๐ช์์ด๋์ด
- ์๊น ๊ตฌ๋ณํ๊ธฐ
- ์ ๋ก์์ฝ์ด ์๋ ์ฌ๋: ์ ์/๋ น์์ด๋ฉด ์ ์๊ณผ ๋ น์์ด ๊ฐ์ ์์ด๋ผ๊ณ ํ์ธ
- ์๋ก์์ฝ์ด ์๋ ์ฌ๋: RGB๋ชจ๋ ๊ตฌ๋ณํจ
- ๊ตฌ์ญ ๊ตฌ๋ณํ๊ธฐ
- ์ ๋ก์์ฝ์ด ์๋ ์ฌ๋์ ์ ์๊ณผ ๋
น์์ ๊ฐ์ ์์ด๋ผ๊ณ ๋ณด๊ธฐ๋๋ฌธ์ bfs์์ ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๊ณณ์ผ ์๋ ์๋ค.
- ์ ๋ก์์ฝ์ด ์๋ ์ฌ๋์ ์ ์๊ณผ ๋
น์์ ๊ตฌ๋ณํ ์ ์๊ธฐ ๋๋ฌธ์ ๋ฐฉ๋ฌธํ์ง ์์ ์ ์์ด ๋ฐ๋ก ๋ฐฉ๋ฌธ์ฒดํฌ๋ฅผ ํด์ค๋ค.
- ์ ๋ก์์ฝ์ด ์๋ ์ฌ๋์ ์ ์๊ณผ ๋
น์์ ๊ฐ์ ์์ด๋ผ๊ณ ๋ณด๊ธฐ๋๋ฌธ์ 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.