leetcode#794. Valid Tic-Tac-Toe State

794. Valid Tic-Tac-Toe State

Problem Description

A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.

The board is a 3 x 3 array, and consists of characters ” “, “X”, and “O”. The ” ” character represents an empty square.

Here are the rules of Tic-Tac-Toe:

  • Players take turns placing characters into empty squares (” “).
  • The first player always places “X” characters, while the second player always places “O” characters.
  • “X” and “O” characters are always placed into empty squares, never filled ones.
  • The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
  • The game also ends if all squares are non-empty.
  • No more moves can be played if the game is over.

Analysis

A direct thought is judging whether the current board is valid. Count all the ‘X’ and all the ‘O’, and it requires num('X') >= num('O') and num('X') - num('O') <= 1. Then we use dp to take a look at which position may be the last step. Then we should check if the game terminates before this step. Here is the code:

class Solution {
public:
    bool validTicTacToe(vector<string>& board) {
        int numX = 0, numO = 0;
        for (int i=0; i<3; i++) {
            for (int j=0; j<3; j++) {
                if (board[i][j] == 'X') numX++;
                if (board[i][j] == 'O') numO++;
            }
        }

        if (numX - numO > 1 || numX - numO < 0) return false;
        if (numO == 0) return true;

        bool flag = false;
        bool choose = numX > numO ? true : false;
        for (int i=0; i<3; i++) {
            for (int j=0; j<3; j++) {
                if (board[i][j] == (choose ? 'X' : 'O')) {
                    vector<string> tmp(board);
                    tmp[i][j] = ' ';
                    if (isValid(tmp)) {
                        flag |= validTicTacToe(tmp);                         
                    }
                }
            }
        }
        return flag;
    }

    bool isValid(vector<string>& board) {
        for (int i=0; i<3; i++) {
            if (board[i][0] != ' ' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) return false;
            if (board[0][i] != ' ' && board[1][i] == board[0][i] && board[2][i] == board[1][i]) return false;
        }
        if (board[0][0] != ' ' && board[1][1] == board[2][2] && board[0][0] == board[1][1]) return false;
        if (board[2][0] != ' ' && board[2][0] == board[1][1] && board[1][1] == board[0][2]) return false;
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值