Trzy funkcje odpowiedzialne za rozwiązanie gotowego arkusza:
bool sudokuBoard::check(int column,int row,int checkedValue)
{
int miniBoxFirstColumn;//0v3v6
int miniBoxFirstRow;//0v3v6
slotType miniBox[3][3];
//column check
for(int i=0; i< 9; i++)
{
if(i==row)continue;
if(checkedValue==slot[column][i].value) return false;
}
//row check
for(int i=0; i<9; i++)
{
if(i==column)
continue;
if(checkedValue==slot[i][row].value) return false;
}
//3x3 box
miniBoxFirstColumn=(column/3)*3;
miniBoxFirstRow=(row/3)*3;
for(int m=0;m<3;m++)
for(int n=0;n<3;n++)
{
if(n==column && m==row) continue;
if(checkedValue == slot[miniBoxFirstColumn+n][miniBoxFirstRow+m].value) return false;
}
return true;
}
void sudokuBoard::resolve()
{
while(!isFull())
{
for(int i=0; i<9; i++)
for(int j=0; j<9; j++)
{
if(slot[j][i].value == 0)
for(int k=1; k<=9; k++)
{
if(check(j,i,k)) //Always false(WHY?);
{
slot[j][i].value=k; //breakpoint
slot[j][i].fixed=false;
}
}
}
}
}
bool sudokuBoard::isFull()
{
for(int i=0; i<9 ; i++)
for(int j=0; j<9; j++)
if(!slot[j][i].value) return false;
return true;
}
Plik nagłówkowy
"sudoku.h"
namespace sudoku
{
struct slotType
{
int value;
bool fixed;
};
class sudokuBoard
{
public:
sudokuBoard operator=(sudokuBoard );
sudokuBoard();
void switchSlotValue(int , int , int);
//column, row, value
void print() const;
void createCustom();
void load();
bool check(int column,int row,int value);
void resolve();
bool isFull();
private:
slotType slot[9][9];
};
}
Funkcja główna:
#include <iostream>
#include "sudokuBoard.h"
using namespace std;
using namespace sudoku;
int MainMenu();
int main(void)
{
sudokuBoard currentBoard;
switch(MainMenu())
{
case 1:
currentBoard.load();
break;
case 2:
currentBoard.createCustom();
break;
}
currentBoard.print();
cout<<"\nResolving...\n";
currentBoard.resolve();
currentBoard.print();
cout<<endl;
system("PAUSE");
return 0;
}
int MainMenu()
{
int choice;
cout<<"Sudoku Wizard (Console version)\n"
<<"1.Load board\n"
<<"2.Create a new board\n";
cin>>choice;
return choice;
}
Plansza
2 0 0 0 6 9 0 4 8
0 0 0 3 0 0 2 7 0
0 7 0 0 2 1 6 9 0
4 0 0 6 0 0 5 0 0
8 0 3 0 1 7 0 0 0
5 0 0 0 0 2 0 0 6
7 9 0 1 0 3 0 0 2
0 4 0 9 0 6 7 0 0
6 0 8 2 0 0 1 0 0
Do rzeczy - ustawiłem breakpointa w najbardziej wewnętrznej pętli funkcji resolve. Dlaczego, dla tego przykładu, osiągany jest on tylko 55 razy, po czym pętla rozwiązuje się w nieskończoność?. Najprawdopodobniej coś jest nie tak z funkcją check...