*Leetcode 794. Valid Tic-Tac-Toe State | 规则

https://leetcode.com/problems/valid-tic-tac-toe-state/description/

本来以为需要搜,想了下 规则应该够 用于练习编程是否心细

class Solution {
public:
    
    int count( vector<string> & board, char c) {
        int ret = 0;
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[i].size(); j++) {
                if (c == board[i][j])
                    ret ++;
            }
        }
        return ret;
    }
    
    int wincnt( vector<string> &board, char c ) {
        int ret = 0;
        // row
        for (int i = 0; i < board.size(); i++) {
            bool check = true;
            for (int j = 0; j < board[i].size(); j++) {
                if (c != board[i][j]) {
                    check = false;
                    break;
                }
            }
            
            if (check)
                ret++;
            
        }
        // col
        for (int i = 0; i < board[0].size(); i++) {
            bool check = true;
            for (int j = 0; j < board.size(); j++) {
                if (board[j][i] != c) {
                    check = false;
                    break;
                }
            }
            if (check)
                ret++;
        }
        
        //
        bool check = true;
        for (int i = 0; i < board.size(); i++) 
            if (board[i][i] != c) {
                check = false;
                break;
            }
        if (check)
            ret++;
        
        if (board[0][2] == c && board[1][1] == c && board[2][0] == c ) {
            ret ++;
        }
        return ret;
        
    }
    
    bool validTicTacToe(vector<string>& board) {
        char x = 'X', o = 'O', sp = ' ';
        int xcnt = count(board, x);
        int ocnt = count(board, o);
        if (xcnt < ocnt || xcnt > ocnt + 1 ) return false;
        int owin = wincnt(board, o), xwin = wincnt(board, x);
        if (owin > 1 || (xwin && owin) ) return false;
        if (xwin && xcnt == ocnt) return false;
        if (owin && xcnt > ocnt) return false;
        return true;
    }
};



猜你喜欢

转载自blog.csdn.net/u011026968/article/details/80918517