Sunday, April 15, 2012

Program 26TH in C++

PROBLEM STATEMENT :

Write a function isValid(int sudoko[][]) to chec whether a given sudoko solution is valid or not.

SOLUTION :

#include <cstdio>
#include <iostream.h>

using namespace std;

//initializing the count array with val.

void reinit(int c[9],int val)
{
for(int i=0; i<9; i++)
{
c[i]=val;
}
}

//checking whether all calues in count array are set to zero or not

bool check (int c[9])
{
for(int i=0; i<9; i++)
{
if(c[i] != 0)
{
return false;
}
}
return true;
}

//function isValid

bool isValid(int a[][9])
{
int i=0;
int j=0;
int k=0;
int p=0;
int count[]={1,1,1,1,1,1,1,1,1};

//checking first 9 blocks for validity

while(k < 9)
{
for(i=k; i<(k+3); i++)
{
for(j=p; j<(p+3); j++)
{
if(a[i][j] > 0 && a[i][j] <10)
{
count[a[i][j]-1]--;

if(count[a[i][j]-1] < 0)
{
return false;
}
}
else
{
return false;
}
}
}
if(check(count))
{
reinit(count,1);
}
else
{

return false;
}

p=p+3;
if(p == 9)
{
p=0;
k=k+3;
}

}
reinit(count,1);
//checking rows for validity

for(i=0; i<9; i++)
{
for(j=0; j<9; j++)
{
if(a[i][j] > 0 && a[i][j] < 10)
{
count[a[i][j]-1]--;
if(count[a[i][j]-1] < 0)
{
return false;
}
}
else
{
return false;
}

if(j == 8 && i!=8)
{
if(check(count))
{
reinit(count,1);
}
else
{
return false;
}
}

}
}
if(check(count))
{
reinit(count,1);
}
else
{
return false;
}

//checking columns for validity

for(j=0 ; j<9 ; j++)
{
for(i=0; i<9; i++)
{
if(a[i][j] > 0 && a[i][j] < 10)
{
count[a[i][j]-1]--;

if(count[a[i][j]-1] < 0)
{
return false;
}
}
else
{
return false;
}
if(i == 8 && j != 8)
{
if(check(count))
{
reinit(count,1);
}
}

}
}

if(check(count))
{
return true;
}
else
{
return false;
}



}

int main()
{

int a[9][9]={{2,4,8,3,9,5,7,1,6},{5,7,1,6,2,8,3,4,9},{9,3,6,7,4,1,5,8,2},{6,8,2,5,3,9,1,7,4},{3,5,9,1,7,4,6,2,8},{7,1,4,8,6,2,9,5,3},{8,6,3,4,1,7,2,9,5},{1,9,5,2,8,6,4,3,7},{4,2,7,9,5,3,8,6,1}};

if(isValid(a))
{
cout<<"true";
}
else
{
cout<<"false";
}
}

No comments:

Post a Comment