Stuck in making a simple sudoku solver

I tried out my following code on an empty grid but the solution was wrong....It contained zeroes :(
I read this backtracking algorithm from Wikipedia.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
#include<array>
using namespace std;
typedef array<array<int,9>,9> Grid;

//void backtrack(int& x,int& y);
bool check(Grid& g, int x, int y, int num); //returns false if num isn't allowed at (x,y)
//void input(Grid& g);
//void output(Grid& g);
int main()
{
    Grid grid;
    int x,y;
    for(x=0;x<9;x++)
	for(y=0;y<9;y++)
	    cin>>grid[x][y];//=0;
     
    bool back_flag(true); //SET to true when stepping backwards
    
    for(int r=0;r<81;)  //using this loop instead of nested x y loop to make backtracking simpler
    {
	x = r/9;
	y = r%9;
	for(int num=1;num<10;num++)
	{
	    if(check(grid,x,y,num))
	    {
		grid[x][y] = num;
		back_flag=false;
		break;
	    }
	}
	if(back_flag)
	    r--;
	else r++;
    }
    
    for(int a=0;a<9;a++)
    {
	for(int b=0;b<9;b++)
	    cout<<grid[a][b]<<" ";
	cout<<endl;
    }
    return 0;
}
bool check(Grid& g, int x, int y, int num)
{
    for(int c=0;c<9;c++)
    {
	if(g[x][c]==num || g[c][y]==num)
	    return false;
    }
    //code below is for checking the local 3x3 grid
    int x_init,y_init;
    x_init = (x/3)*3;
    y_init = (y/3)*3;
    for(int x_index = x_init; x_index< x_init+3 ; x_index++)
	for(int y_index = y_init; y_index< y_init+3; y_index++)
	{
	    if(g[x_index][y_index]==num)
		return false;
	}
    
    return true;
}

Is there a problem in my understanding of the algorithm or in the logic of the implementation ?

NB: Compile with C++0x flags for std::array
Last edited on
You got some little mistakes on your for loop. :P
i didn't compile with c++0x so i just used a regular array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
for(int r=0;r<81;)  //using this loop instead of nested x y loop to make backtracking simpler
{
        bool back_flag = true; //declare as local variable for the loop
        x = r/9;
        y = r%9;
        for(int num = grid[x][y]; num < 10; num++)
        {
            if(num == 0)
                continue;
            //do smth to check if the value is user-inputted

            if(check(grid,x,y,num))
            {
                grid[x][y] = num;
                back_flag=false;
                break;
            }
            else if(num >= 9)
            {
                grid[x][y] = 0;
            }
        }
        if(back_flag)
            r--;
        else
            r++;
 }
Last edited on
Thank you.
Last edited on
Topic archived. No new replies allowed.