Simple O(1) time C++ solution following provided hints


  • 14
    A
    class TicTacToe {
    public:
        TicTacToe(int n) : sz(n) {
            rows.resize(n, 0), cols.resize(n, 0);
            diagonal = anti_diagonal = 0;
        }
        
        int move(int row, int col, int player) {
            if (player == 1) {
                ++rows[row], ++cols[col];
                if (row == col)
                    ++diagonal;
                if (row == sz - 1 - col)
                    ++anti_diagonal;
                if (rows[row] == sz || cols[col] == sz || diagonal == sz || anti_diagonal == sz)
                    return 1;
            }
            else {
                --rows[row], --cols[col];
                if (row == col)
                    --diagonal;
                if (row == sz - 1 - col)
                    --anti_diagonal;
                if (rows[row] == -sz || cols[col] == -sz || diagonal == -sz || anti_diagonal == -sz)
                    return 2;
            }
            return 0;
        }
    
    private:
        vector<int> rows, cols;
        int diagonal, anti_diagonal;
        int sz;
    };

  • 0
    I

    this fails testcase

    ["TicTacToe","move","move","move","move","move","move","move"]
    [[3],[0,0,1],[0,2,2],[2,2,1],[1,1,2],[2,0,1],[1,0,2],[2,1,1]]


  • 1
    V

    So far the best implementation that I've seen.


  • 0
    A

    @vogelkaka Thank you!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.