Validity of a given Tic-Tac-Toe board configuration - GeeksforGeeks

06 Apr, 2022
A Tic-Tac-Toe board is given after some moves are played. Find out if the given board is valid, i.e., is it possible to reach this board position after some moves or not.Note that every arbitrary filled grid of 9 spaces isn’t valid e.g. a grid filled with 3 X and 6 O isn’t valid situation because each player needs to take alternate turns. 
Input is given as a 1D array of size 9. Examples:  
Input: board[] =  {'X', 'X', 'O', 
                   'O', 'O', 'X',
                   'X', 'O', 'X'};
Output: Valid

Input: board[] =  {'O', 'X', 'X', 
                   'O', 'X', 'X',
                   'O', 'O', 'X'};
Output: Invalid
(Both X and O cannot win)

Input: board[] =  {'O', 'X', ' ', 
                   ' ', ' ', ' ',
                   ' ', ' ', ' '};
Output: Valid
(Valid board with only two moves played)
 
Basically, to find the validity of an input grid, we can think of the conditions when an input grid is invalid. Let no. of “X”s be countX and no. of “O”s be countO. Since we know that the game starts with X, a given grid of Tic-Tac-Toe game would be definitely invalid if following two conditions meet a) countX != countO AND b) countX != countO + 1Since “X” is always the first move, second condition is also required.Now does it mean that all the remaining board positions are valid one? The answer is NO. Think of the cases when input grid is such that both X and O are making straight lines. This is also not valid position because the game ends when one player wins. So we need to check the following condition as well c) If input grid shows that both the players are in winning situation, it’s an invalid position. d) If input grid shows that the player with O has put a straight-line (i.e. is in win condition) and countX != countO, it’s an invalid position. The reason is that O plays his move only after X plays his move. Since X has started the game, O would win when both X and O has played equal no. of moves. e) If input grid shows that X is in winning condition than xCount must be one greater that oCount.Armed with above conditions i.e. a), b), c) and d), we can now easily formulate an algorithm/program to check the validity of a given Tic-Tac-Toe board position. 
1)  countX == countO or countX == countO + 1
2)  If O is in win condition then check 
     a)     If X also wins, not valid
     b)     If xbox != obox , not valid
3)  If X is in win condition then check if xCount is
     one more than oCount or not  
Another way to find the validity of a given board is using ‘inverse method’ i.e. rule out all the possibilities when a given board is invalid. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check whether a given tic tac toe// board is valid or not#include <iostream>using namespace std; // This matrix is used to find indexes to check all// possible winning triplets in board[0..8]int win[8][3] = {{0, 1, 2}, // Check first row.                {3, 4, 5}, // Check second Row                {6, 7, 8}, // Check third Row                {0, 3, 6}, // Check first column                {1, 4, 7}, // Check second Column                {2, 5, 8}, // Check third Column                {0, 4, 8}, // Check first Diagonal                {2, 4, 6}}; // Check second Diagonal // Returns true if character 'c' wins. c can be either// 'X' or 'O'bool isCWin(char *board, char c){    // Check all possible winning combinations    for (int i=0; i<8; i++)        if (board[win[i][0]] == c &&            board[win[i][1]] == c &&            board[win[i][2]] == c )            return true;    return false;} // Returns true if given board is valid, else returns falsebool isValid(char board[9]){    // Count number of 'X' and 'O' in the given board    int xCount=0, oCount=0;    for (int i=0; i<9; i++)    {    if (board[i]=='X') xCount++;    if (board[i]=='O') oCount++;    }     // Board can be valid only if either xCount and oCount    // is same or count is one more than oCount    if (xCount==oCount || xCount==oCount+1)    {        // Check if 'O' is winner        if (isCWin(board, 'O'))        {            // Check if 'X' is also winner, then            // return false            if (isCWin(board, 'X'))                return false;             // Else return true xCount and yCount are same            return (xCount == oCount);        }         // If 'X' wins, then count of X must be greater        if (isCWin(board, 'X') && xCount != oCount + 1)        return false;         // If 'O' is not winner, then return true        return true;    }    return false;} // Driver programint main(){char board[] = {'X', 'X', 'O',                'O', 'O', 'X',                'X', 'O', 'X'};(isValid(board))? cout << "Given board is valid":                    cout << "Given board is not valid";return 0;}
// Java program to check whether a given tic tac toe// board is valid or not class GFG { // This matrix is used to find indexes to check all// possible winning triplets in board[0..8]    static int win[][] = {{0, 1, 2}, // Check first row.    {3, 4, 5}, // Check second Row    {6, 7, 8}, // Check third Row    {0, 3, 6}, // Check first column    {1, 4, 7}, // Check second Column    {2, 5, 8}, // Check third Column    {0, 4, 8}, // Check first Diagonal    {2, 4, 6}}; // Check second Diagonal // Returns true if character 'c' wins. c can be either// 'X' or 'O'    static boolean isCWin(char[] board, char c) {        // Check all possible winning combinations        for (int i = 0; i < 8; i++) {            if (board[win[i][0]] == c                    && board[win[i][1]] == c                    && board[win[i][2]] == c) {                return true;            }        }        return false;    } // Returns true if given board is valid, else returns false    static boolean isValid(char board[]) {        // Count number of 'X' and 'O' in the given board        int xCount = 0, oCount = 0;        for (int i = 0; i < 9; i++) {            if (board[i] == 'X') {                xCount++;            }            if (board[i] == 'O') {                oCount++;            }        }         // Board can be valid only if either xCount and oCount        // is same or count is one more than oCount        if (xCount == oCount || xCount == oCount + 1) {            // Check if 'O' is winner            if (isCWin(board, 'O')) {                // Check if 'X' is also winner, then                // return false                if (isCWin(board, 'X')) {                    return false;                }                 // Else return true xCount and yCount are same                return (xCount == oCount);            }             // If 'X' wins, then count of X must be greater            if (isCWin(board, 'X') && xCount != oCount + 1) {                return false;            }             // If 'O' is not winner, then return true            return true;        }        return false;    } // Driver program    public static void main(String[] args) {        char board[] = {'X', 'X', 'O', 'O', 'O', 'X', 'X', 'O', 'X'};         if ((isValid(board))) {            System.out.println("Given board is valid");        } else {            System.out.println("Given board is not valid");        }    }}//this code contributed by PrinciRaj1992
# Python3 program to check whether a given tic tac toe# board is valid or not # Returns true if char wins. Char can be either# 'X' or 'O'def win_check(arr, char):    # Check all possible winning combinations    matches = [[0, 1, 2], [3, 4, 5],               [6, 7, 8], [0, 3, 6],               [1, 4, 7], [2, 5, 8],               [0, 4, 8], [2, 4, 6]]     for i in range(8):        if(arr[matches[i][0]] == char and            arr[matches[i][1]] == char and            arr[matches[i][2]] == char):            return True    return False def is_valid(arr):    # Count number of 'X' and 'O' in the given board    xcount = arr.count('X')    ocount = arr.count('O')         # Board can be valid only if either xcount and ocount    # is same or count is one more than oCount    if(xcount == ocount+1 or xcount == ocount):        # Check if O wins        if win_check(arr, 'O'):            # Check if X wins, At a given point only one can win,            # if X also wins then return Invalid            if win_check(arr, 'X'):                return "Invalid"             # O can only win if xcount == ocount in case where whole            # board has values in each position.            if xcount == ocount:                return "Valid"         # If X wins then it should be xc == oc + 1,        # If not return Invalid            if win_check(arr, 'X') and xcount != ocount+1:            return "Invalid"                 # if O is not the winner return Valid        if not win_check(arr, 'O'):            return "Valid"             # If nothing above matches return invalid    return "Invalid"  # Driver Codearr = ['X', 'X', 'O',       'O', 'O', 'X',       'X', 'O', 'X']print("Given board is " + is_valid(arr))
// C# program to check whether a given// tic tac toe board is valid or notusing System; class GFG{ // This matrix is used to find indexes// to check all possible winning triplets// in board[0..8]public static int[][] win = new int[][]{    new int[] {0, 1, 2},    new int[] {3, 4, 5},    new int[] {6, 7, 8},    new int[] {0, 3, 6},    new int[] {1, 4, 7},    new int[] {2, 5, 8},    new int[] {0, 4, 8},    new int[] {2, 4, 6}}; // Returns true if character 'c'// wins. c can be either 'X' or 'O'public static bool isCWin(char[] board,                          char c){    // Check all possible winning    // combinations    for (int i = 0; i < 8; i++)    {        if (board[win[i][0]] == c &&            board[win[i][1]] == c &&            board[win[i][2]] == c)        {            return true;        }    }    return false;} // Returns true if given board// is valid, else returns falsepublic static bool isValid(char[] board){    // Count number of 'X' and    // 'O' in the given board    int xCount = 0, oCount = 0;    for (int i = 0; i < 9; i++)    {        if (board[i] == 'X')        {            xCount++;        }        if (board[i] == 'O')        {            oCount++;        }    }     // Board can be valid only if either    // xCount and oCount is same or count    // is one more than oCount    if (xCount == oCount ||        xCount == oCount + 1)    {        // Check if 'O' is winner        if (isCWin(board, 'O'))        {            // Check if 'X' is also winner,            // then return false            if (isCWin(board, 'X'))            {                return false;            }             // Else return true xCount            // and yCount are same            return (xCount == oCount);        }         // If 'X' wins, then count of        // X must be greater        if (isCWin(board, 'X') &&            xCount != oCount + 1)        {            return false;        }         // If 'O' is not winner,        // then return true        return true;    }    return false;} // Driver Codepublic static void Main(string[] args){    char[] board = new char[] {'X', 'X', 'O', 'O', 'O',                                    'X', 'X', 'O', 'X'};     if ((isValid(board)))    {        Console.WriteLine("Given board is valid");    }    else    {        Console.WriteLine("Given board is not valid");    }}} // This code is contributed by Shrikant13
<?php// PHP program to check whether a given// tic tac toe board is valid or not // This matrix is used to find indexes// to check all possible winning triplets// in board[0..8] // Returns true if character 'c' wins.// c can be either 'X' or 'O'function isCWin($board, $c){    $win = array(array(0, 1, 2), // Check first row.                 array(3, 4, 5), // Check second Row                 array(6, 7, 8), // Check third Row                 array(0, 3, 6), // Check first column                 array(1, 4, 7), // Check second Column                 array(2, 5, 8), // Check third Column                 array(0, 4, 8), // Check first Diagonal                 array(2, 4, 6)); // Check second Diagonal                      // Check all possible winning combinations    for ($i = 0; $i < 8; $i++)        if ($board[$win[$i][0]] == $c &&            $board[$win[$i][1]] == $c &&            $board[$win[$i][2]] == $c )            return true;    return false;} // Returns true if given board is// valid, else returns falsefunction isValid(&$board){    // Count number of 'X' and 'O'    // in the given board    $xCount = 0;    $oCount = 0;    for ($i = 0; $i < 9; $i++)    {        if ($board[$i] == 'X') $xCount++;        if ($board[$i] == 'O') $oCount++;    }     // Board can be valid only if either    // xCount and oCount is same or count    // is one more than oCount    if ($xCount == $oCount || $xCount == $oCount + 1)    {        // Check if 'O' is winner        if (isCWin($board, 'O'))        {            // Check if 'X' is also winner,            // then return false            if (isCWin($board, 'X'))                return false;             // Else return true xCount and            // yCount are same            return ($xCount == $oCount);        }         // If 'X' wins, then count of X        // must be greater        if (isCWin($board, 'X') &&                   $xCount != $oCount + 1)        return false;         // If 'O' is not winner, then        // return true        return true;    }    return false;} // Driver Code$board = array('X', 'X', 'O','O',               'O', 'X','X', 'O', 'X');if(isValid($board))    echo("Given board is valid");else    echo ("Given board is not valid");     // This code is contributed// by Shivi_Aggarwal?>
<script>// Javascript program to check whether a given// tic tac toe board is valid or not // This matrix is used to find indexes// to check all possible winning triplets// in board[0..8] // Returns true if character 'c' wins.// c can be either 'X' or 'O'function isCWin(board, c){    let win = new Array(new Array(0, 1, 2), // Check first row.                new Array(3, 4, 5), // Check second Row                new Array(6, 7, 8), // Check third Row                new Array(0, 3, 6), // Check first column                new Array(1, 4, 7), // Check second Column                new Array(2, 5, 8), // Check third Column                new Array(0, 4, 8), // Check first Diagonal                new Array(2, 4, 6)); // Check second Diagonal                     // Check all possible winning combinations    for (let i = 0; i < 8; i++)        if (board[win[i][0]] == c &&            board[win[i][1]] == c &&            board[win[i][2]] == c )            return true;    return false;} // Returns true if given board is// valid, else returns falsefunction isValid(board){    // Count number of 'X' and 'O'    // in the given board    let xCount = 0;    let oCount = 0;    for (let i = 0; i < 9; i++)    {        if (board[i] == 'X') xCount++;        if (board[i] == 'O') oCount++;    }     // Board can be valid only if either    // xCount and oCount is same or count    // is one more than oCount    if (xCount == oCount || xCount == oCount + 1)    {        // Check if 'O' is winner        if (isCWin(board, 'O'))        {            // Check if 'X' is also winner,            // then return false            if (isCWin(board, 'X'))                return false;             // Else return true xCount and            // yCount are same            return (xCount == oCount);        }         // If 'X' wins, then count of X        // must be greater        if (isCWin(board, 'X') &&                xCount != oCount + 1)        return false;         // If 'O' is not winner, then        // return true        return true;    }    return false;} // Driver Codelet board = new Array('X', 'X', 'O','O',            'O', 'X','X', 'O', 'X');if(isValid(board))    document.write("Given board is valid");else    document.write("Given board is not valid");     // This code is contributed// by Saurabh Jaiswal</script>
Output: 
Given board is valid
Thanks to Utkarsh for suggesting this solution.  
YouTubeGeeksforGeeks507K subscribersValidity of a given Tic-Tac-Toe board configuration | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=RqOFx7Waehc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
jaysiyaram
princiraj1992
shrikanth13
Shivi_Aggarwal
gfgking
sumitgumber28
simmytarika5
Amazon
Microsoft
Arrays
Matrix
Amazon
Microsoft
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)