Question

I've heard about backtracking and I've searched a little bit .I thought I got the idea and wrote this piece of code to solve sudoku , but it seems to give wrong solutions (for example repeated numbers in a row) , what exactly i am doing wrong here ?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>


#define N 9

bool not_in_row(int temp , int i , int grid[N][N]){

int f ;
for(f = 0 ; f < N ; f++)
    if(grid[i][f] == temp)
        return false ;
return true ;
 }

bool not_in_column(int temp , int j , int grid[N][N]){

int f ;
for(f = 0 ; f < N ; f++)
    if(grid[f][j] == temp)
        return false ;
return true ;
}


bool not_in_sq(int i , int j , int grid[N][N] , int temp){

int k , t ; 
int s = i - (i % 3) + 3, v = j - (j % 3) + 3;
for(k =  i - (i % 3) ; i < s ; i++)
    for(t = j - (j % 3) ; j < v ; j++)
        if(grid[k][t] == temp)
          return false ;
return true ;
       }


bool sudoku_Solver(int grid[N][N] , int position){



if(position == 81)
    return true ;
int i = position / 9 , j = position % 9 ;

if(grid[i][j] != 0)
    return sudoku_Solver(grid , position + 1) ;


else{

int temp ;

for(temp = 1 ; temp <= N ; temp++){
    if(not_in_row(temp , i , grid) && not_in_column(temp , j , grid) && not_in_sq(i , j , grid , temp))
    {
        grid[i][j] = temp ;
        if(sudoku_Solver(grid , position + 1))
                return true ;
            }
                }

            }
grid[i][j] = 0 ;    
return false ;
}


int main(int argc, char *argv[]) {

int i , j ;
int grid[9][9] = {{0,1,0,0,4,0,0,0,0}
                 ,{6,0,0,0,0,0,0,1,8}
                 ,{0,0,0,1,0,9,0,3,2}
                 ,{2,0,5,0,0,3,8,0,0}
                 ,{0,0,0,0,0,0,0,0,0}
                 ,{0,0,4,7,0,0,1,0,5}
                 ,{8,6,0,2,0,5,0,0,0}
                 ,{4,2,0,0,0,0,0,0,9}
                 ,{0,0,0,0,3,0,0,7,0}
                    } ;

sudoku_Solver(grid , 0) ;

for(i = 0 ; i < 9 ; i++){
    for(j = 0 ; j < 9 ; j++){
        printf("%d " , grid[i][j]) ;
                }
    printf("\n") ;
        } 
return 0;
       }
Was it helpful?

Solution

Your loops in not_in_sq are wrong:

for(k =  i - (i % 3) ; i < s ; i++)
    for(t = j - (j % 3) ; j < v ; j++)

Look closely at i < s, i++, j < v, and j++. They are obviously incorrect. Here they are fixed:

for(k =  i - (i % 3) ; k < s ; k++)
    for(t = j - (j % 3) ; t < v ; t++)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top