[英]Backtracking in C
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;
}
Your loops in not_in_sq
are wrong:您在
not_in_sq
中的循环是错误的:
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++
.仔细观察
i < s
、 i++
、 j < v
和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++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.