#include <bits/stdc++.h>
using namespace std;
int arr[9][9];
bool isSafeRow(int row, int value)
{
for (int i = 0; i < 9; ++i)
{
if(arr[row][i]==value)
return true;
}
return false;
}
bool isSafeColumn(int col, int value)
{
for (int i = 0; i < 9; ++i)
{
if(arr[i][col]==value)
return true;
}
return false;
}
bool isSafeBox(int startRow, int startCol, int value)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if (arr[startRow+i][startCol+j]==value)
{
return true;
}
}
}
return false;
}
bool isSafe(int row, int col, int value)
{
return !isSafeRow(row,value) && !isSafeColumn(col,value) && !isSafeBox(row-row%3,col-col%3,value);
}
bool sudoku()
{
int row,col;
int flag = 0;
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
if (arr[i][j]==0)
{
row = i;
col = j;
flag = 1;
//printf("Test1...\n");
break;
}
}
if (flag)
{
break;
}
}
if (!flag)
{
return true;
}
/*if(!unassignedLocation(row,col))
{
return true;
}*/
//printf("%d %d\n",row,col);
for (int digit = 1; digit <= 9; ++digit)
{
//printf("New... %d\n",isSafe(row,col,digit));
if(isSafe(row,col,digit))
{
//printf("Test\n");
arr[row][col] = digit;
if(sudoku())
return true;
arr[row][col] = 0;
}
}
return false;
}
int main()
{
while(1)
{
printf("Enter (-1,-1,-1) to quit otherwise enter index i,j,value\n");
int i,j,value;
scanf("%d%d%d",&i,&j,&value);
if(i==-1 || j==-1 || value==-1)
{
break;
}
arr[i][j] = value;
}
if(sudoku())
{
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
printf("%2d ",arr[i][j]);
}
printf("\n");
}
}
else
{
printf("No Solution Exist\n");
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.