Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Sunday, June 17, 2018

Check if TicTacToe is valid


Problem :
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.
X will be move first

https://practice.geeksforgeeks.org/problems/tic-tac-toe/0

here we are having few cases :

IF x count==o it means o should win and if x wins then it will be invalid.
IF x count==o+1 it means x will win , in that case if o wins then it will be invalid 
IF xcount-o count !=1 || 0 it means invalid
Else valid 

Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class validTicToe
 {
   public static boolean wins(char a[],char t)
   {
     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
                 for(int i=0;i<8;++i)
                 {
                   if(a[win[i][0]]==t && a[win[i][1]]==t && a[win[i][2]]==t)
                   return true;
                 }
                 return false;
   }
  public static boolean isValid(char a[])
  {
    int o=0,x=0;
    for(int i=0;i<9;++i)
    {
      if(a[i]=='X')
      ++x;
      else
      ++o;
    }
    if(x==o)
    {
      //System.out.println("eq");
      if(wins(a,'X'))
      return false;
    }
    else if(x==o+1)
    {
    //  System.out.println("x>");
      if(wins(a,'O'))
      return false;
      return true;
    }
    return false;
  }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
    char arr[]=new char[9];
    for(int i=0;i<9;++i)
    arr[i]=ab.next().charAt(0);
    System.out.println(isValid(arr));
}
}
}

0 Comments:

Post a Comment

Stats