Is Sudoku Valid | Practice | GeeksforGeeks

Given an incomplete Sudoku configuration in terms of a 9x9  2-D square matrix(mat[][]) the task to check if the current configuration is valid or not where a 0 represents an empty block.
Note: Current valid configuration does not ensure validity of the final solved sudoku. 
Refer to this : https://en.wikipedia.org/wiki/Sudoku
Example 1:
Input: mat[][] = [
[3, 0, 6, 5, 0, 8, 4, 0, 0]
[5, 2, 0, 0, 0, 0, 0, 0, 0]
[0, 8, 7, 0, 0, 0, 0, 3, 1]
[0, 0, 3, 0, 1, 0, 0, 8, 0]
[9, 0, 0, 8, 6, 3, 0, 0, 5]
[0, 5, 0, 0, 9, 0, 6, 0, 0]
[1, 3, 0, 0, 0, 0, 2, 5, 0]
[0, 0, 0, 0, 0, 0, 0, 7, 4]
[0, 0, 5, 2, 0, 6, 3, 0, 0]
]
Output: 1
Explaination: It is possible to have a
proper sudoku.
Your Task:
You do not need to read input or print anything. Your task is to complete the function isValid() which takes mat[][] as input parameter and returns 1 if any solution is possible. Otherwise, returns 0.
Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(1)
Constraints:
0 ≤ mat[i][j] ≤ 9
0
patildhiren441 week ago
JAVA  - 3.08 
static boolean isValidSudoku(int[][] board) {
        
        for(int i=0; i<board.length; i++){
            
            HashSet<Integer> row = new HashSet<>();
            HashSet<Integer> col = new HashSet<>();
            HashSet<Integer> cube = new HashSet<>();
            
            for(int j=0; j<board[0].length; j++){
                
                if(board[i][j]!=0 && !row.add(board[i][j])){
                    return false;
                }
                
                if(board[j][i]!=0 && !col.add(board[j][i])){
                    return false;
                }
                
                int RowIndex = 3*(i/3);
                int ColIndex = 3*(i%3);
                if(board[RowIndex + j/3][ColIndex + j%3]!=0 && !cube.add(board[RowIndex + j/3][ColIndex + j%3]))
                    return false;

            }
        }
        return  true;
    }
    
    static int isValid(int mat[][]){
        // code here
        
        if(isValidSudoku(mat)){
            return 1;
        }
        return 0;
    }
-1
patelneer4031 month ago
int i,j;              for(i=0;i<9;i++)       {           unordered_map<int,int>map;           for(j=0;j<9;j++)           {               if(mat[i][j]==0)               continue;            map[mat[i][j]]++;            if(map[mat[i][j]]>1 && mat[i][j]!=0)            return 0;                          }                  }              for(i=0;i<9;i++)       {           unordered_map<int,int>map;           for(j=0;j<9;j++)           {               if(mat[j][i]==0)               continue;                           map[mat[j][i]]++;            if(map[mat[j][i]]>1 && mat[j][i]!=0)            return 0;                          }                  }              for(int k=0;k<9;k+=3)       {           for(int l=0;l<9;l+=3)           {               i=k;                unordered_map<int,int>map;                              while(i!=k+3)               {                                     j=l;                   while(j!=l+3)                   {                       if(mat[i][j]==0){                       j++;                       continue;                       }                       map[mat[i][j]]++;                                             if(map[mat[i][j]] >1  && mat[i][j]!=0)                       return 0;                                               j++;                   }                                                         i++;               }                                         }                  }                            return 1;                     
0
madhukartemba2 months ago
INTUITIVE JAVA SOLUTION: 
class Solution{
    static int isValid(int mat[][])
    {
        
        HashSet<Integer> hs = new HashSet<>();
        
        int n = 9;
        
        //Check for the rows
        for(int i=0; i<n; i++)
        {
            hs.clear();
            for(int j=0; j<n; j++)
            {
                int x = mat[i][j];
                
                if(x!=0)
                {
                    if(hs.contains(x)) return 0;
                    else hs.add(x);
                }
            }
        }
        
        //Check for the columns
        for(int i=0; i<n; i++)
        {
            hs.clear();
            for(int j=0; j<n; j++)
            {
                int x = mat[j][i];
                
                if(x!=0)
                {
                    if(hs.contains(x)) return 0;
                    else hs.add(x);
                }
            }
        }
        
        //Check for the sub-squares
        for(int i=0; i<n; i+=3)
        {
            for(int j=0; j<n; j+=3)
            {
                hs.clear();
                for(int k=i; k<i+3; k++)
                {
                    for(int l=j; l<j+3; l++)
                    {
                        int x = mat[k][l];
                        
                        if(x!=0)
                        {
                          if(hs.contains(x)) return 0;
                          else hs.add(x);
                        }
                    }
                }
            }
        }
        
        
        //All passed
        return 1;
        
        
    }
}
+2
palakkotwani28833 months ago
Time Complexity:O(N^2)
Space Complexity:O(1)
 
//Checking if the same value exist in same row and same col
bool isValid(vector<vector<int>>mat,int row,int col){
   for(int i=0;i<9;i++){
       if(i!=row && mat[i][col]==mat[row][col])
       return false;
       if(i!=col && mat[row][i]==mat[row][col])
       return false;
       if(((3*(row/3)+i/3)!=row ) &&((3*(col/3)+i%3)!=col) && mat[3*(row/3)+i/3][3*(col/3)+i%3]==mat[row][col])
       return false;
   }
   return true;
}

   int isValid(vector<vector<int>> mat){
       // code here
      for(int i=0;i<9;i++){
          for(int j=0;j<9;j++){
if(mat[i][j]==0)
continue;
              if( isValid(mat,i,j))
              continue;
              else{
                
              
              return 0;
              }
          }
      }
      
      return 1;
   }
};
+1
utsavbhatia3 months ago
class Solution{
    static int isValid(int mat[][]){
        HashSet<String> set = new HashSet<>();
        for(int i=0;i<9;++i) {
            for(int j=0;j<9;++j) {
                if(mat[i][j]!=0) {
                    if(!set.add(mat[i][j]+"r"+i) ||
                    !set.add(mat[i][j]+"c"+j) ||
                    !set.add(mat[i][j]+"b"+(i/3)+"_"+(j/3)))
                        return 0;
                }
            }
        }
        return 1;
    }
}
0
abdulkhn83 months ago
Soultion in Java -
-----------------
 
class Solution{   static int isValid(int mat[][]){       // code here       for(int row=0;row<9;row++)       {            for(int col=0;col<9;col++)           {               if(mat[row][col] != 0 && !isSafe(mat,row,col))               {                   return 0;               }           }        }       return 1;   }      static boolean isSafe(int mat[][],int rowIndex,int colIndex)   {       //row and col check       for(int i=0;i<9;i++)       {           //row check           if(mat[rowIndex][colIndex]==mat[rowIndex][i] &&                colIndex!=i)           {               return false;           }           //col check           if(mat[rowIndex][colIndex]==mat[i][colIndex] &&               rowIndex!=i)           {               return false;           }       }              //current board check       int r = rowIndex-rowIndex%3;       int c = colIndex-colIndex%3;       for( int i=0;i< 3;i++)       {            for(int j=0;j<3;j++)           {               if(mat[rowIndex][colIndex]==mat[r+i][c+j] &&                   rowIndex!=r+i &&                   colIndex!=c+j)               {                   return false;               }           }        }       return true;   }}
0
amanpandey30073 months ago
int isValid(vector<vector<int>> mat)   {               for(int i=0;i<9;i++)      {             vector<int>arr(10,-1);          for(int j=0;j<9;j++)          {              if(mat[i][j]==0)              continue;                            else if(arr[mat[i][j]]==-1)              arr[mat[i][j]]=mat[i][j];                            else              return 0;          }      }            for(int j=0;j<9;j++)      {             vector<int>arr(10,-1);          for(int i=0;i<9;i++)          {              if(mat[i][j]==0)              continue;                            else if(arr[mat[i][j]]==-1)              arr[mat[i][j]]=mat[i][j];                            else              return 0;          }      }            for(int i=0;i<9;i+=3)      {          for(int j=0;j<9;j+=3)          {                 vector<int>arr(10,-1);              for(int a=0;a<3;a++)              {                     for(int b=0;b<3;b++)                  {                     if(mat[i+a][j+b]==0)                      continue;                                    else if(arr[mat[i+a][j+b]]==-1)                      arr[mat[i+a][j+b]]=mat[i+a][j+b];                                    else                      return 0;                   }              }          }      }            return 1;   }
0
krishna1saini13 months ago
    int isValid(vector<vector<int>> mat){       // code here       int visit[10] = {0};              //row       for(int i=0 ; i<9 ; i++)       {           for(int j=0 ; j<9 ; j++)           {               if(mat[i][j] == 0)                   continue;                                  if(visit[mat[i][j]])                   return 0;               visit[mat[i][j]] = 1;           }                      for(int i=0 ; i<10 ; i++)               visit[i] = 0;       }              //column       for(int i=0 ; i<9 ; i++)       {           for(int j=0 ; j<9 ; j++)           {               if(mat[j][i] == 0)                   continue;                              if(visit[mat[j][i]])                   return 0;               visit[mat[j][i]] = 1;           }                      for(int i=0 ; i<10 ; i++)               visit[i] = 0;       }             for(int i=0 ; i<10 ; i++)               visit[i] = 0;       //3*3             int rs=0 , re = 3 , cs = 0 , ce = 3;              while( 1 )       {           int i , j;           for( i = rs ; i<re ; i++)           {               for( j=cs ; j<ce ; j++)               {                   if(mat[i][j] == 0)                      continue;                                         if(visit[mat[i][j]])                      return 0;                   visit[mat[i][j]] = 1;               }           }                      for(int i=0 ; i<10 ; i++)             visit[i] = 0;                        cs = ce;           ce = cs+3;           if(cs == 9 && re!=9)           {               rs = re;               re = rs+3;               cs = 0;               ce = cs+3;           }           else if(cs==9 && re==9)           {               return 1;           }       }   }
0
rounkagrwl3 months ago



C++ , Time - O(N*N), Space - O(1)
#include <bits/stdc++.h>
using namespace std;


// User function Template for C++

class Solution{
public:
    int isValid(vector<vector<int>> mat){
        int maxi = 15;
        int n=9;
        
        //setting the matrix
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                
                int temp = mat[i][j]%maxi;
                if(temp){
                mat[i][temp-1]+=maxi;
                if(mat[i][temp-1]/maxi>1) 
                    return false;}
            }
        }
        
        //resetting the matrix
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                mat[i][j] = mat[i][j]%maxi;
            }
        }
        
        //setting the matrix
        for(int j=0;j<n;j++){
            for(int i=0;i<n;i++){
                
                int temp = mat[i][j]%maxi;
                if(temp){
                mat[temp-1][j]+=maxi;
                if(mat[temp-1][j]/maxi>1)
                    return false;}
            }
        }
        //Resetting the matrix
        
         for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                mat[i][j] = mat[i][j]%maxi;
            }
        }
        
        
        //setting the matrix
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
               int i1 = i/3;
               int j1= j/3;
            int in;
             if(i1==0)  in = j1;
             if(i1==1)  in = 3+j1;
             if(i1==2)  in = 6+j1;
               int temp = mat[i][j]%maxi;
                if(temp){
                mat[in][temp-1]+=maxi;
                if(mat[in][temp-1]/maxi>1) 
                    return false;}
            }
        }
        
        return true;
    }
};

// { Driver Code Starts.

int main(){
    int t;
    cin>>t;
    while(t--){
        vector<vector<int>> mat(9, vector<int>(9, 0));
        for(int i = 0;i < 81;i++)
            cin>>mat[i/9][i%9];
        
        Solution ob;
        cout<<ob.isValid(mat)<<"\n";
    }
    return 0;

}  // } Driver Code Ends
0
choudharyaakash0663 months ago
#Performing Simple Checks
class Solution:
    def isValid(self, mat):
        # code here
        rowCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}
        colCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}
        gridCheck = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}
        
        for i in range(len(mat)):
            for j in range(len(mat)):
                check = mat[i][j]
                if check != 0:
                    if check in rowCheck[i] or check in colCheck[j]:
                        return 0
                    rowCheck[i].append(check)
                    colCheck[j].append(check)
                    
                    grid = (i//3)*3 + (j//3)
                    
                    if check in gridCheck[grid]:
                        return 0
                    gridCheck[grid].append(check)
        return 1
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.