백준 1018번 파이썬 - 체스판
- 개발 스터디/백준 문제풀이
- 2024. 6. 17.
반응형
728x90
반응형
문제 정보
답
초안
n, m = map(int, input().split())
chessPlate = []
for i in range(n):
row = input()
chessPlate.append(row)
result = []
for j in range(len(chessPlate)):
if chessPlate[j].count('W') == 4 and chessPlate[j].count('B') == 4:
res = 0
result.append(res)
elif chessPlate[j].count('B') > 4 and chessPlate[j].count('W') < 4:
res = 4 - chessPlate[j].count('W')
result.append(res)
elif chessPlate[j].count('W') > 4 and chessPlate[j].count('B') < 4:
res = 4 - chessPlate[j].count('B')
result.append(res)
elif chessPlate[j].count('W') == chessPlate[j].count('B'):
res = 0
result.append(res)
else:
res = abs(chessPlate[j].count('W') - chessPlate[j].count('B'))-1
result.append(res)
print(sum(result))
처음 초안을 이렇게 코딩을 했다.
문제점으로 최소값을 구할 수 가 없었다.
그래서 함수를 만들어 해결해 보기로 했다.
최종 답안
n, m = map(int, input().split()) # 보드의 크기 N과 M 입력
chessPlate = []
for i in range(n):
row = input() # 각 행의 상태 입력
chessPlate.append(row) # 보드를 리스트에 추가
def count_repaints(board, start_row, start_col, first_color):
repaints = 0
color = first_color
for i in range(start_row, start_row + 8): # 8x8 영역의 행 순회
for j in range(start_col, start_col + 8): # 8x8 영역의 열 순회
if board[i][j] != color: # 현재 칸의 색이 올바르지 않으면
repaints += 1 # 다시 칠하기 횟수 증가
color = 'B' if color == 'W' else 'W' # 다음 칸의 예상 색
color = 'B' if color == 'W' else 'W' # 다음 행의 첫 칸 색
return repaints
min_repaints = float('inf') # 최소 다시 칠하기 횟수를 무한대로 초기화
for i in range(n - 7): # 가능한 모든 8x8 시작 행 순회
for j in range(m - 7): # 가능한 모든 8x8 시작 열 순회
repaints_W = count_repaints(chessPlate, i, j, 'W') # 왼쪽 위가 흰색인 경우
repaints_B = count_repaints(chessPlate, i, j, 'B') # 왼쪽 위가 검은색인 경우
min_repaints = min(min_repaints, repaints_W, repaints_B) # 최소 횟수 업데이트
print(min_repaints) # 결과 출력
이 코드는 다음과 같은 순서로 작동한다.
- count_repaints 함수는 특정 8x8 영역을 주어진 시작 색 (first_color)에 맞게 칠하기 위해 필요한 다시 칠하기 횟수를 계산
- 이 함수는 8x8 영역의 각 칸을 순회하면서 올바른 색인지 확인하고, 잘못된 경우 다시 칠하는 횟수를 증가시킴
- 메인 루프에서는 보드의 모든 8x8 가능한 영역에 대해 count_repaints 함수를 호출하여 두 가지 경우(왼쪽 위가 흰색 또는 검은색)에 대해 각각 다시 칠해야 하는 횟수를 계산
- 모든 경우 중에서 최소 다시 칠하기 횟수를 찾음
728x90
반응형
'개발 스터디 > 백준 문제풀이' 카테고리의 다른 글
백준 1259번 팰린드롬수 문제풀이 : 파이썬 (0) | 2024.06.17 |
---|---|
백준 1181번 단어 정렬 파이썬 풀이 (0) | 2024.06.17 |
백준 4101번 문제풀이 (1) | 2024.06.10 |
백준 3733번 문제 풀이 (1) | 2024.06.10 |
백준 3003번 문제 풀이 (0) | 2024.06.10 |