[백준] 2615번 오목

반디·2023년 8월 31일
0

코테스터디

목록 보기
11/11

문제링크: https://www.acmicpc.net/problem/2615

아이디어

  1. 바둑판의 좌측 상단에서 우측 하단으로 이동해가며 승자를 판단
    이 때, 오른쪽 위 대각선, 오른쪽, 오른쪽 아래 대각선, 아래방향을 탐색하며 진행

  2. 연속되는 5개의 돌을 찾았다면, 제일 끝 돌에서 해당 방향으로 한번 더 탐색하여 & 제일 첫번째 돌에서 현재 방향의 반대 방향으로 한번 더 육목이 되는 지 여부를 확인

코드

import sys
input = sys.stdin.readline

SIZE: int = 19
def init_data():
    boards = [list(map(int, input().split())) for _ in range(SIZE)]
    return boards

class Board():
    def __init__(self, board_map = None, size: int = SIZE) -> None:
        if board_map == None:
            raise Exception(f"{self.__class__} {sys._getframe().f_code.co_name}: there is no board_map")
        self.board_map = board_map
        self.size = size
        
    def in_range(self, pos = None):
        if pos == None:
            raise Exception(f"{self.__class__} {sys._getframe().f_code.co_name}: there is no pos")
    
        if 0 <= pos[0] < SIZE and 0 <= pos[1] < SIZE:
            return True
        return False 
    
    def line_check(self, pos = None, color: int=1):
        if pos == None:
            raise Exception(f"{self.__class__} {sys._getframe().f_code.co_name}: there is no pos")
    
        DXS = [-1, 0, 1, 1]
        DYS = [1, 1, 0, 1]
        x, y = pos
        for i in range(4): #왼쪽 상단부터 오른쪽 하단으로 탐색하므로, 오른쪽, 오른쪽 아래 대각선, 아래, (오른쪽 위 대각선?) 탐색 
            cnt = 1
            nx = x+DXS[i]
            ny = y+DYS[i]
            
            while self.in_range([nx, ny]) and self.board_map[nx][ny] == color:
                cnt += 1
                
                if cnt == 5:
                    if self.in_range([nx+DXS[i], ny+DYS[i]]) and self.board_map[nx+DXS[i]][ny+DYS[i]] == color:
                        break
                    if self.in_range([x-DXS[i], y-DYS[i]]) and self.board_map[x-DXS[i]][y-DYS[i]] == color:
                        break

                    return True, color, [x+1, y+1]
                
                nx += DXS[i]
                ny += DYS[i]

        return False, 0, []
            
    def winner_check(self):
        for i in range(self.size):
            for j in range(self.size):
                if self.board_map[i][j] != 0:
                    flag, color, pos = self.line_check([i, j], self.board_map[i][j])
                    if flag == True:
                        print(color)
                        print(*pos)
                        return 
        print(0)
        return 

if __name__ == '__main__':
    boards = Board(init_data())
    boards.winner_check()

결과

고려해야하는 점

  • 우측 상단 대각선 방향도 탐색해야 하는 이유
    오목을 이루는 상황을 생각했을 때, 다음과 같은 케이스가 있기 때문에 우측 상단 대각선 방향도 포함해서 탐색해줘야 함!
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
1 0 0 0 0 
profile
꾸준히!

0개의 댓글