Given an incomplete Sudoku configuration in terms of a 9x9 2-D square matrix (mat[][]) the task to check if the configuration has a solution or not. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Tuesday, 2 June 2020

Given an incomplete Sudoku configuration in terms of a 9x9 2-D square matrix (mat[][]) the task to check if the configuration has a solution or not.

Given an incomplete Sudoku configuration in terms of a 9x9  2-D square matrix (mat[][]) the task to check if the configuration has a solution or not. 

Here is simple and easy approach with hashing using unordered_set,that execute in 0.01s.

#include <bits/stdc++.h>
using namespace std;
int isvalid(int a[9][9])
{
    for(int i=0;i<9;++i)
    {
        unordered_set<int> s;
        for(int j=0;j<9;++j)
        {
            if((a[i][j]!=0)&&(!s.count(a[i][j])))
//value not equal to zero and count is zero.
s.insert(a[i][j]); else if((a[i][j]!=0)&&(s.count(a[i][j])))
//value not equal to zero and count is greater zero.
return 0; } } for(int i=0;i<9;++i) { unordered_set<int> s; for(int j=0;j<9;++j) { if((a[j][i]!=0)&&(!s.count(a[j][i])))
//value not equal to zero and count is zero.
s.insert(a[j][i]); else if((a[j][i]!=0)&&(s.count(a[j][i])))
//value not equal to zero and count is greater zero.
return 0; } }
//It is optional for 3*3 ,without this also code executed with 0.01s
     for(int i=0;i<9;i=i+3)
    {
        
        for(int j=0;j<9;j=j+3)
        {
            unordered_set<int> s;
            for(int k=i;k<i+3;++k)
            {
            
            for(int l=j;l<j+3;++l)
            if((a[k][l]!=0)&&(!s.count(a[k][l]))) 
//value not equal to zero and count is zero.
            s.insert(a[k][l]);
            else if((a[k][l]!=0)&&(s.count(a[k][l])))
//value not equal to zero and count is greater zero.
            return 0;
            }
        }
        
    }
    
     return 1;
}

int main() {

	int t;
	cin>>t;
	while(t--)
	{
	  
	    
	  int a[9][9],f;
	  for(int i=0;i<9;++i)
	  {
	      for(int j=0;j<9;++j)
	      {
	          cin>>a[i][j];
	      }
	      
	  }
	  
	  
	   if(isvalid(a))
	  cout<<1<<endl;
	  else
	  cout<<0<<endl;
	}
	return 0;
}