Sudoku square problem

Hello, i`ve made sudoku project. Problem is in the square. There have been two or three same numbers.

Sudoku table before:
0 1 0 0 0 0 0 0 0
0 0 0 5 0 0 0 0 0
0 0 0 0 0 0 0 0 3
0 0 0 0 0 0 0 2 0
0 0 0 8 0 0 0 0 0
0 0 0 0 0 4 0 0 0
0 0 0 0 0 0 0 0 0
0 0 9 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
Sudoku table after
2 1 3 4 6 7 5 8 9
4 6 8 5 5 9 1 7 2
5 9 7 1 2 8 4 6 3
1 3 4 5 7 6 9 2 8
6 7 2 8 9 1 3 4 5
9 8 5 2 3 4 6 1 7
3 2 1 6 8 5 7 9 4
7 5 9 9 4 2 8 3 1
8 4 9 7 1 3 2 5 6
Press any key to continue . . .

Problematic part of code:

bool sudoku_square(int row,int column){
int square_row = row/3;
int square_column = column/3;

for (int i = square_row*3; i < (square_row*3 + 3); i++){

for (int j = square_column*3; j < (square_column*3 + 3); j++){

if (!(i == row && j == column)){

if (matrix[ row ][column ].number == matrix[i][j].number)
return false;
}
}
}
return true;
}
Last edited on
Hi Niksy50,

Please always user code tags, the small <> icon on the right of the text box.

Can you post your entire code, the piece of code you posted is out of contexte, therefore it's hard to identify what's wrong with it
I don't see anything wrong with your posted snippet.
The problem must be elsewhere.
struct Sudoku{
int number;
bool pr;
} matrix[9][9];

void sudoku_table() {
matrix[0][1].number = 1;
matrix[1][3].number = 4;
matrix[2][8].number = 7;
matrix[3][7].number = 5;
matrix[4][4].number = 9;
matrix[6][8].number = 3;
matrix[7][1].number = 6;

for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
cout << matrix[i][j].number << " ";
}
cout << endl;
}
}
bool s_row(int row,int column){
for(int j=0;j<9;j++){
if(j!=column)
if(matrix[row][j].number == matrix[row][column].number)
return false;
}
return true;
}
bool s_column(int row,int column){
for(int i=0;i<9;i++){
if(i!=row)
if(matrix[i][column].number == matrix[row][column].number)
return false;
}
return true;
}
bool solve(int row, int column){
while (matrix[row][column].pr == true) //provjera redaka i stupaca matrice
{
column++;
if(column > 8){
column = 0;
row++;
}
if (row> 8){
return true;
}
}
for (int n = 1; n < 10; n++){ //upis brojeva u 2d matricu
int nextrow, nextcolumn;
matrix[row][column].number= n;
if ( s_row(row, column)
&& s_stupca(row, column)&& sudoku_square(row,column)){
nextrow = row;
nextcolumn = column;
nextcolumn++;
if(nextcolumn > 8){
nextcolumn = 0;
nextrow++;
}
if(nextcolumn==0 && nextrow ==9){
return true;
}
if(solve(nextrow,nextcolumn)){
return true;
}
}
}
matrix[row][column].number = 0;
return false;
}
You should always post your code in code tags: http://www.cplusplus.com/forum/articles/16853/

You should post a complete program, including headers and main.

However, I added a main (and your sudoku_square function from the first post) and the program works for me. The solution is correct .
Topic archived. No new replies allowed.