Jeg lavede en sudoku løser i C++, den bruger recursion, det er næsten så simpelt som det kan blive:
#include <iostream>
#include <vector>
typedef unsigned char uint8_t;
struct SudokuT
{
uint8_t Maze[9][9];
};
SudokuT Maze = // This is the sudoko to solve
{
{
{7,8,0,0,0,5,9,0,0},
{0,4,0,2,0,7,0,3,0},
{0,5,9,0,0,8,2,4,0},
{0,2,0,0,0,9,3,1,0},
{0,0,7,3,0,4,6,0,0},
{0,3,4,1,0,0,0,9,0},
{0,6,5,7,0,0,8,2,0},
{0,7,0,9,0,6,0,5,0},
{0,0,3,5,0,0,0,7,6}
}
};
bool IsValid(const SudokuT &aSudoko, int aX, int aY, uint8_t aVal)
{ // Will the sudoko be valid if we put aVal into [aX][aY]
int a;
for(a = 0; a < 9; a++)
if(aSudoko.Maze[aX][a] == aVal)
return false;
for(a = 0; a < 9; a++)
if(aSudoko.Maze[a][aY] == aVal)
return false;
int y = aY/3;
int x = aX/3;
if(aSudoko.Maze[x*3][y*3 + 0] == aVal || aSudoko.Maze[x*3 + 1][y*3 + 0] == aVal || aSudoko.Maze[x*3 + 2][y*3 + 0] == aVal ||
aSudoko.Maze[x*3][y*3 + 1] == aVal || aSudoko.Maze[x*3 + 1][y*3 + 1] == aVal || aSudoko.Maze[x*3 + 2][y*3 + 1] == aVal ||
aSudoko.Maze[x*3][y*3 + 2] == aVal || aSudoko.Maze[x*3 + 1][y*3 + 2] == aVal || aSudoko.Maze[x*3 + 2][y*3 + 2] == aVal)
{
return false;
}
return true;
}
bool Solve(SudokuT &aSudoko)
{
int x, y;
uint8_t Val;
for(y = 0; y < 9; y++)
{
for(x = 0; x < 9; x++)
{
if(aSudoko.Maze[x][y] == 0)
{ // Have found a empty index, check all values
for(Val = 1; Val <= 9; Val++)
{
if(IsValid(aSudoko, x, y, Val))
{
aSudoko.Maze[x][y] = Val;
if(Solve(aSudoko))
return true;
}
}
aSudoko.Maze[x][y] = 0;
return false;
}
}
}
return true;
}
int main()
{
if(Solve(Maze))
{
std::cout << "Success" << std::endl;
int x, y;
for(y = 0; y < 9; y++)
{
for(x = 0; x < 9; x++)
std::cout << int(Maze.Maze[y][x]);
std::cout << std::endl;
}
}
else
{
std::cout << "Failed" << std::endl;
}
}
Man kunne optimere på to punkter:
1: Når man skal finde en tom plads startes der altid forfra.
2: Måden man finder ud af hvilke tal der kan bruges på en plads, kunne optimeres ved at starte med at lave en liste over mulige tal, så skulle man kun søge gennem én gang.