본문 바로가기
백준 풀이

[백준/BOJ] - 1303번 python 풀이 - dfs

by 반오십 코린이 2023. 3. 13.
728x90

 


문제를 계속 풀면서 느낀점

- 보통 실패가 떴을 때 예외는 테스트 케이스가 1,1 같은 경우에 잘 생긴다.

 

문자 값을 2차원 배열에 삽입할 때 사용하는 문법

arr = [list(input()) for _ in range(m)]

import sys
sys.setrecursionlimit(1000000)
n,m = map(int,input().split()) #가로, 세로
arr = [list(input()) for _ in range(m)]
ok = [[False] * n for i in range(m)]
W = []
B = []
dx,dy = (-1,1,0,0), (0,0,-1,1)
cnt = 0 
total1 = 0
total2 = 0
def dfs(x,y,team):
    global cnt
    cnt+=1
    ok[x][y] = True #방문처리
    for i in range(4):
        rx = x + dx[i]
        ry = y + dy[i]
        # 처음 dfs 접근했을때 값과 arr[rx][ry]의 값이 같은지
        if (0<=rx<m) and (0<=ry<n) and arr[rx][ry] == team:
            #방문 하지 않았을 경우
            if not ok[rx][ry]:
                dfs(rx,ry,team)


for i in range(m):
    for j in range(n):
        if not ok[i][j]: # if false
            dfs(i, j, arr[i][j])
            if arr[i][j] == 'W': # W team
                W.append(cnt**2) #제곱해서 리스트에 삽입                
            else: # B team
                B.append(cnt**2)
            cnt = 0 #cnt 초기화

for item in W:
    total1 += item
for item in B:
    total2 += item
print(total1, total2)

 

728x90