[LeetCode] 1275. Find Winner on a Tic Tac Toe Game

Chobby·2025년 7월 30일
1

LeetCode

목록 보기
485/582

😎풀이

  1. moves를 순회한다.
  2. X를 시작으로 O와 번갈아가며 해당 좌표에 수를 둔다.
  3. 둔 수를 포함하여 승리 조건을 탐색한다.
    3-1. 해당 수의 행이 모두 같은 플레이어의 수 인가?
    3-2. 해당 수의 열이 모두 같은 플레이어의 수 인가?
    3-3. 해당 수의 대각선이 모두 같은 플레이어의 수 인가?
  4. 승리 조건을 먼저 만족한 플레이어가 승리한다.
  5. 모두 순회할 때까지 게임이 종료되지 않았다면 다음 조건을 수행한다.
    5-1. 9칸이 모두 채워졌다면 무승부
    5-2. 아니라면 진행중
type TurnType = 'X' | 'O'
function tictactoe(moves: number[][]): string {
    let curTurn: TurnType = 'X'
    const matrix = Array.from({ length: 3 }, () => Array(3).fill(''))
    for(const [y, x] of moves) {
        matrix[y][x] = curTurn
        const winFlag = isWin({
            curMatrix: matrix,
            curTurn,
            curX: x,
            curY: y
        })
        if(winFlag) return curTurn === 'X' ? 'A' : 'B'
        curTurn = curTurn === 'X' ? 'O' : 'X'
    }
    return moves.length === 9 ? 'Draw' : 'Pending'
};

function isWin({
    curMatrix,
    curTurn,
    curX,
    curY
}: {
    curMatrix: string[][]
    curTurn: TurnType;
    curX: number;
    curY: number;
}) {
    let vertical = 0
    let horizontal = 0
    let lrDiagonal = 0
    let rlDiagonal = 0
    // 가로, 세로 검사
    for(let i = 0; i < 3; i++) {
        if(curMatrix[i][curX] === curTurn) vertical++
        if(curMatrix[curY][i] === curTurn) horizontal++
        if(curMatrix[i][i] === curTurn) lrDiagonal++
        if(curMatrix[i][3 - (i + 1)] === curTurn) rlDiagonal++
    }
    if(vertical === 3) return true
    if(horizontal === 3) return true
    if(lrDiagonal === 3) return true
    if(rlDiagonal === 3) return true
    return false
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글