So, it could solve puzzles of certain level but not all. Take a look into this puzzle, which my code isn't able to solve.
- Code: Select all
9 0 5 0 0 0 0 0 8
4 0 0 5 7 0 1 0 6
0 2 7 6 0 0 0 4 0
0 9 6 0 0 3 5 1 2
7 0 4 0 1 0 3 0 0
2 1 0 9 8 0 0 0 4
0 8 1 0 0 4 0 9 0
3 0 0 8 0 0 0 5 1
0 0 2 0 0 7 0 6 0
So, here is the brute force code I have written... could you please help me to catch the bug in it.
- Code: Select all
# include <stdio.h>
# include "lib.h"
extern int sudoku[size][size];
extern int TempArr[size][size];
int i, j, n;
int BruteForce (void)
{
int val;
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
if (sudoku[i][j]==0)
{
for (n=1; n<nmax; n++)
{
val = check(i,j,n);
if (val==1)
{
sudoku[i][j]=n;
// output();
break;
}
else if (n==nmax-1 && val == 0)
back();
}
}
}
}
}
int back(void)
{
int iback,jback,flag=0;
sudoku[i][j]=0;
for (iback=i; iback>=0; iback--)
{
for (jback=j; jback>=0; jback--)
{
if (!(iback==i && jback==j) && TempArr[iback][jback]==0)
{
flag=0;
if (sudoku[iback][jback]==nmax-1)
sudoku[iback][jback]=0;
else
{
n=sudoku[iback][jback];
sudoku[iback][jback]=0;
i = iback; j = jback;
flag=1;
break;
}
}
}
if (flag==1)
break;
}
}
Code description:
1. This code follows brute force algorithm as mentioned in wikipedia.
2. sudoku[][] is the input sudoku file, TempArr[][] is a copy of that which I use for reference.
3. check(i,j,n): If it returns 1 => n can be assigned to sudoku[i][j] or else if it returns 0, it can't be assigned.
code>>
First, the loop starts iterating from i=0, j=0.. if it finds an empty cell ( i.e, 0 ), it enters into another loop which starts iterating from 1 to 9 (nmax=10, so.. nmax-1=9). If check() return 1 for any value, it assigns and goes to another empty cell.
For a particular cell, if check() doesn't return 1 from n=1 to nmax-1 (9), it goes back to the previous empty cell and starts iterating from where it left and continues. This is where we need TempArr[][] to locate previous empty cell.
Please help me!