Question

I have a problem of an application writed in C for Sudoku solver for 9x9 boxes, it's use recursion to solve and find all the combinations, however I added one line of debugging and I found the problem but I don't know why:

The problem it's on this line:

for(k=1;k<=9;k++)
if(valid(k,i,j))
{
    printf("\nPozition %d %d takes valor %d.",i,j,k);
    v[i][j]=k;
    bt();
}

The all code is here:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std; 
int v[200][200];
void afisare()
{
    for(int i=1;i<=9;i++){
    for(int j=1;j<=9;j++)
    printf("%2d",v[i][j]);
    printf("\n");
}
    printf("\n");
}

int valid(int k,int ii,int jj)
{
    int i,j;
   for(i=1;i<=9;i++)
   for(j=1;j<=9;j++)
    {
        if((i!=ii || j!=jj) && v[i][j]==k)
        return 0;
    }
    return 1;
} 

void bt()
{
    int i,j,k,ok=0;

    for(i=1;i<=9;i++){
    for(j=1;j<=9;j++)
    if(v[i][j]==0)
    {
        ok=1;
        break;
    }

    if(ok)
    break;
    }

    if(!ok)
    {
        afisare();
        return;
    }

    for(k=1;k<=9;k++)
    if(valid(k,i,j))
    {
        printf("\nPozition %d %d takes valor %d.",i,j,k);
        v[i][j]=k;
        bt();
    }
    v[i][j]=0;
}
int main()
{
    int i,j;
    freopen("sudoku.in","r",stdin);
//  freopen("rezultat.out","w",stdout);
    for(i=1;i<=9;i++)
    for(j=1;j<=9;j++)
    scanf("%d",&v[i][j]);

    for(i=1;i<=9;i++){
    for(j=1;j<=9;j++)
    printf("%2d",v[i][j]);
    printf("\n");
}

    bt();
    system("pause");
    return 0;
}

I read information from sudoku.in; I put empty boxes with 0.

The printf debugging sound's like this:

Pozition 1 7 takes valor 8
Pozition 1 8 takes valor 7
pozition 1 9 ...

etc... I saw that there are only from 5 so position 1 5/ 1 6/ 1 7 etc.. And the variable i in for isn't going to 2...

Forgot to mention ( Function "Afisare" means "Printing" the solution)

Was it helpful?

Solution

The problem may be in valid().

int valid(int k,int ii,int jj)
{
    int i,j;
    for(i=1;i<=9;i++)
        for(j=1;j<=9;j++)
        {
            if((i!=ii || j!=jj) && v[i][j]==k)
                return 0;
        }
    return 1;
} 

According to your implementation, if v[1][1] == 1, then v[9][9] cannot be 1. This does not make sense at all.

What you want should be:

int valid(int k, int ii, int jj)
{
    int i;
    for(i = 1; i <= 9; ++i) {
        if (i != ii && v[i][jj] == k)
            return 0;
        if (i != jj && v[ii][i] == k)
            return 0;
    }
    return 1;
}

Also note that you still need to take care of 3x3 blocks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top