본문 바로가기

알고리즘 문제풀이

백준 1018 체스판 다시 칠하기 Python 브루트포스 실버4

정답 코드: 시작점이 검은색이냐, 흰색이냐로 구분해서 해결 함

N, M = map(int,input().split())
chess = [list(input()) for _ in range(N)]
count = []

for a in range(N-7):
    for b in range(M-7):
        black = 0
        whilte = 0
        for i in range(a, a+8):
            for j in range(b, b+8):
                if (i+j) % 2 == 0: # 짝수면 시작점과 색깔이 같다
                    if chess[i][j] != 'W':
                        black += 1
                    if chess[i][j] != 'B':
                        whilte += 1
                else: # 홀수면 시작점과 색깔이 다르다
                    if chess[i][j] != 'B':
                        black += 1
                    if chess[i][j] != 'W':
                        whilte += 1
        count.append(min(black, whilte))

print(min(count))

검색 전 직접 알고리즘 구상한 내용, 4방향 탐색을 이용해서 하려고 했음.

시작점의 색을 바꿀 수 있을 수 없다고 가정하고 풀었기 때문에, 테스트 케이스에서 하나가 맞지 않게 풀림

import copy
dij = [[0,1],[1,0]] # 오 밑 왼 위
n,m = map(int,input().split())
chess = [list(input()) for _ in range(n)]
print(chess)
min_cnt = 64
for i in range(n-7):
    for j in range(m-7):
        cnt = 0
        chess_copy = copy.deepcopy(chess)
        for x in range(8):
            for y in range(8):
                for k in range(2):
                    ni = i+x + dij[k][0]
                    nj = j+y + dij[k][1]
                    if 0 <= ni < i+8 and 0 <= nj < j+8: # 벽체크
                        if chess_copy[i+x][j+y] == chess_copy[ni][nj]:
                            cnt += 1
                            if chess_copy[ni][nj] == 'B':
                                chess_copy[ni][nj] = 'W'
                            else:
                                chess_copy[ni][nj] = 'B'
        if min_cnt > cnt:
            min_cnt = cnt
        print(i,j,cnt)
print(min_cnt)