[파이썬] 백준 1303 : 전쟁 - 전투 (실버1)
1303번: 전쟁 - 전투
첫째 줄에는 전쟁터의 가로 크기 N, 세로 크기 M(1 ≤ N, M ≤ 100)이 주어진다. 그 다음 두 번째 줄에서 M+1번째 줄에는 각각 (X, Y)에 있는 병사들의 옷색이 띄어쓰기 없이 주어진다. 모든 자리에는
www.acmicpc.net
문제
풀이
방향성 생각
- 군집 크기 구하기. 기본적인 BFS / DFS 문제
DFS
from collections import deque
import sys
input = lambda : sys.stdin.readline().rstrip()
w,h = map(int,input().split())
arr = [list(input()) for _ in range(h)]
visit = [[False]*w for _ in range(h)]
def dfs(x,y,c):
if x<0 or y<0 or x>=w or y>=h:
return 0
if not visit[y][x] and arr[y][x]==c:
visit[y][x] = True
return 1+dfs(x-1,y,c)+dfs(x+1,y,c)+dfs(x,y-1,c)+dfs(x,y+1,c)
return 0
info = [0,0]
for i in range(h):
for j in range(w):
if arr[i][j] == 'W':
info[0] += dfs(j,i,'W')**2
if arr[i][j] == 'B':
info[1] += dfs(j,i,'B')**2
print(*info)
- 재귀야 항상 하던대로, 탈출조건 적어주기. 맵 밖에 벗어나는 경우는 탐색 x
- 맵 안쪽인 경우에는 방문처리 안된 경우, 같은 색깔인 경우에만 진행.
- 출력은 언패킹으로 한 번에
BFS
from collections import deque
import sys
input = lambda : sys.stdin.readline().rstrip()
w,h = map(int,input().split())
arr = [list(input()) for _ in range(h)]
visit = [[False]*w for _ in range(h)]
dire = [(1,0),(-1,0),(0,1),(0,-1)]
def bfs(x,y):
count,color = 1,arr[y][x]
visit[y][x] = True
q = deque([(x,y)])
while q:
x,y = q.popleft()
for dx,dy in dire:
nx = x + dx
ny = y + dy
if 0<=nx<w and 0<=ny<h and not visit[ny][nx] and color == arr[ny][nx]:
q.append((nx,ny))
visit[ny][nx] = True
count += 1
return count**2
info = [0,0]
for i in range(h):
for j in range(w):
if not visit[i][j]:
if arr[i][j] == 'W':
info[0] += bfs(j,i)
else:
info[1] += bfs(j,i)
print(*info)
- dfs로 같은 색깔인 경우에 탐색을 진행한다.
- 맵 내부에 들어온 경우 방문하지 않은 인접한 같은색깔 노드를 탐색한다.
- count 전부 해주고, 제곱해서 리턴.
- BFS로 격자 순회하면서 방문하지 않은 노드에서 BFS 진행
- 출력은 언패킹
코멘트
기본 알고리즘 웰노운 문제들은 10분 언저리면 실수없이 푸는듯?
실수해도 실수 할만한 부분들을 알아서 디버깅도 빠르다
'Algorithm > Graph' 카테고리의 다른 글
[파이썬] 백준 2251: 물통 (골드5) (0) | 2023.11.21 |
---|---|
[파이썬] 백준 2206 : 벽 부수고 이동하기 (골드3) (0) | 2023.11.16 |
[파이썬] 백준 1926 : 그림 (실버1) (0) | 2023.11.10 |
[파이썬] 백준 1833 : 고속철도 설계하기 (골드3) (0) | 2023.11.05 |
[파이썬] 백준 2151 : 거울설치 (골드3) (0) | 2023.10.08 |
[파이썬] 백준 1068 : 트리 (골드5) (0) | 2023.09.14 |
[파이썬] 백준 16437: 양 구출 작전 (골드3) (0) | 2023.09.11 |
댓글