Sudoku is a popular single player game. The objective is to fill a 9×9 matrix with digits so that each column, each row, and all 9 non-overlapping 3×3 sub-matrices contain all of the digits from 1 through 9. Each 9×9 matrix is partially completed at the start of game play and typically has a unique solution.
Given a completed NxN Sudoku matrix, your task is to determine whether it is a valid solution. A valid solution must satisfy the following criteria:
- Each row contains each number from 1 to N, once each.
- Each column contains each number from 1 to N, once each.
- Divide the NxN matrix into N non-overlapping sqrt(N)xsqrt(N) sub-matrices. Each sub-matrix contains each number from 1 to N, once each.
Sudoku — Valid configuration or not
Write a program to just check if the given matrix is a valid sudoku solution.
Input Format
The first line of the input consists of an integer that corresponds to N. The next N lines describe a completed Sudoku solution, with each line contains exactly N integers. All input integers are positive and less than 1000.
Assume that N is always a perfect square and it is not greater than 64.
Output Format
Print “yes” (quotes for clarity only) if it is a valid solution, or “no” (quotes for clarity only) if it is invalid.
Sample Input 1:
4
1 2 3 4
3 4 1 2
2 1 4 3
4 3 2 1
Sample Output 1:
yes
Sample Input 2:
4
1 2 3 4
2 1 4 3
3 4 1 2
4 3 2 1
Sample Output 2:
no
Solution
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int n;
int checkgrid(int **a,int row,int col,int check1,int sum)
{ int i,j;
//sauravhathi
for(i=row;i<(row+sqrt(n));i++)
for(j=col;j<(col+sqrt(n));j++)
{
if(!(a[i][j]>=1 && a[i][j]<=n)){return 1;}
check1=check1+a[i][j];
}
if(sum!=check1)return 1;
return 0;
}
int main()
{ int sum=0,check1=0,check2=0,flag=0,i,j;
scanf("%d",&n);
//sauravhathi
if(n%2==0) sum=(pow(n,2)/2)+(n/2);
else sum=(n-(n/2))*n;
int **a=(int**)malloc(sizeof(int*)*n);
for(i=0;i<n;i++)a[i]=malloc(n*sizeof(int));
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<n;i++)
{ check1=0;check2=0;
for(j=0;j<n;j++)
{
if(!(a[i][j]>=1&&a[i][j]<=n)){printf("no");
return 0;}
check1+=a[i][j];check2+=a[j][i];
}
if(check1!=sum||check2!=sum) {flag=1;break;}
}
if(flag!=1)
{
//sauravhathi
for(i=0;i<n;i=i+sqrt(n))
for(j=0;j<n;j=j+sqrt(n))
{
flag=checkgrid(a,i,j,0,sum);
if(flag){printf("no");return 0;}
}
}
if(flag)printf("no");
else printf("yes");
return 0;
//sauravhathi
}
Happy Learning – If you require any further information, feel free to contact me.