# is there anything wrong in sudoku logic ?

• 08-09-2011
suryak
is there anything wrong in sudoku logic ?
I'm using brute force algo.
here PossValue() tells whether the number N can be place or not.
It returns 1 if it can be placed.. it returns 0 if it can't

- What I tried to do here is...
go to an empty cell (I took 0 as i/p for empty ) and place a possible value N.
then go to next empty cell and do it..
if there exists a cell that can't take any value from 1-9 then go back to previous cell and choose another possible value ( this I did by incrementing from where I stopped..)..

This is my code..
when I compile and provided i/p its not doing nothing.. neither displaying o/p nor showing error not getting into infinite loop..

Code:

// initial value of K is 0

for (i=0; i<9; i++)
{  printf("?");
for (j=0; j<9; j++)
{
if (sudoku[i][j] == 0)
{  printf("(%d,%d)",i,j);
for (n=1+k; n<10; n++)
{
flag1 = 0;
if ( PossValue(i,j,n) == 1 )
{
sudoku[i][j] = n;
break;
}
else if (PossValue(i,j,n) == 0)
{
flag1 = 1;
}
}
}
if (flag1 == 1)
{
if(j >= 1)
{
j = j-1;
k = sudoku[i][j];
}
else if (j=0)
{
i = i-1;
j = 8;
k = sudoku[i][j];
}
}
}
}

• 08-09-2011
Salem
> else if (j=0)
Well this will mess up the logic.
Try ==

Here's a first test.
Create a completed sudoku grid, remove just one number, and then see if your program can 'solve' it.
• 08-09-2011
suryak
No, Salem..
It the same..
• 08-09-2011
suryak
but the rest of the code is fine ??
If so, I'll look at other part.. but right now .. I am not able to find.
• 08-09-2011
Salem
Did you try my test?
Did it work?
If not, then use the debugger to step through the code. It shouldn't take too long to step through the code to where it's trying to fill in the single missing cell.

BTW, most of the effort is down to you.

Most helpers don't have the time to construct a test program around a single function, then guess what input data might make the code fail in the exact way that you're seeing. If it's anything more complicated than copy/paste, don't expect anyone to bother with trying to RUN your code. At best, you're just going to get a few minutes of eyeball time over the code.
• 08-09-2011
iMalc
The problem probably cannot be solved from only that limited code snippet.
Fix the problem you've been told about and and make sure that you don't decrement i below zero.
Oh and the way you are trying to backtrack will not work anyway. You aren't undoing all of the wrong moves made. Recursion would be a better option.