본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1275. Find Winner on a Tic Tac Toe Game

반응형

https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/description/

 

Find Winner on a Tic Tac Toe Game - LeetCode

Can you solve this real interview question? Find Winner on a Tic Tac Toe Game - Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares ' '. * The first player A

leetcode.com

간단 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

moves에 따른 결과를 확인하기 위한 vector board를 선언 후 moves의 원소를 순회하며 값을 조건에 맞게 채워줍니다.

📔 풀이과정

4방향을 검사해 승자를 가려야 합니다.

loop를 수행하며 다음 방향으로 연속 3개의 같은 문자가 나왔는지 확인해 줍니다.

|, ㅡ, /, \

* game이 진행중이면 board에 값이 모두 차지 않았으므로 Pending을 반환해주면 됩니다.


📕 Code

📔 C++

class Solution {
public:
    string tictactoe(vector<vector<int>>& moves) {
        vector <vector<char>> board(3, vector<char>(3));
        for(int i = 0; i < moves.size(); i++) {
            if(i % 2 == 0) board[moves[i][0]][moves[i][1]] = 'X';
            else board[moves[i][0]][moves[i][1]] = 'O';
        }
        
        int xCnt = 0, oCnt = 0;
        // ㅡ, | 검사
        for(int i = 0; i < 3; i++) {
            xCnt = 0, oCnt = 0;
            for(int j = 0; j < 3; j++) {
                if(board[i][j] == 'X') xCnt++;
                else if(board[i][j] == 'O') oCnt++;
                if(xCnt == 3 && oCnt == 3) return "Draw";
                if(xCnt == 3) return "A";
                if(oCnt == 3) return "B";
            }
            xCnt = 0, oCnt = 0;
            for(int j = 0; j < 3; j++) {
                if(board[j][i] == 'X') xCnt++;
                else if(board[j][i] == 'O') oCnt++;
                if(xCnt == 3 && oCnt == 3) return "Draw";
                if(xCnt == 3) return "A";
                if(oCnt == 3) return "B";
            }
        }
        // '\' 검사
        xCnt = 0, oCnt = 0;
        for(int i = 0; i < 3; i++) {
            if(board[i][i] == 'X') xCnt++;
            else if(board[i][i] == 'O') oCnt++;
            if(xCnt == 3) return "A";
            if(oCnt == 3) return "B";
        }
        // '/' 검사
        xCnt = 0, oCnt = 0;
        for(int i = 0; i < 3; i++) {
            if(board[i][2-i] == 'X') xCnt++;
            else if(board[i][2-i] == 'O') oCnt++;
            if(xCnt == 3) return "A";
            if(oCnt == 3) return "B";
        }
        
        return moves.size() == 9 ? "Draw" : "Pending";
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.