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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
#include <iostream>
using namespace std;
//Chequing if it has a solut
int ifposible(int SudokuArray[][9], int row, int col, int num)
{
//declaring variables rowini to get the columns location later on with the loop
//if row is, exa: row 1, it'll be like: 1/3*3, therefore es row 1, and the same with row 2, ...
int rowIni = (row / 3) * 3;
int colBegining = (col / 3) * 3;
int i, j;
// consider digits 1 to 9
for (i = 0; i<9; ++i)
{
if (SudokuArray[row][i] == num) return false; //If false
if (SudokuArray[i][col] == num) return false;
if (SudokuArray[rowIni + (i % 3)][colBegining + (i / 3)] == num) return false; // Checks whether it can assign num to the row or col
}
return true; // return, if success
}
int completeSudoku(int SudokuArray[][9], int row, int col)
{
//In case the everything is good in terms of rows and columns
int i;
if (row<9 && col<9)
{
if (SudokuArray[row][col] != 0) //If they don't = 0, then add 1 using recursive
{
if ((col + 1)<9)
return completeSudoku(SudokuArray, row, col + 1); //filling 9 the 9 spaces
else if ((row + 1)<9)
return completeSudoku(SudokuArray, row + 1, 0);
else return 1;
}
else
{
//if the numbers don't match it goes back to the previus function to check
for (i = 0; i<9; ++i)
{
if (ifposible(SudokuArray, row, col, i + 1))
{
SudokuArray[row][col] = i + 1;
if ((col + 1)<9)
{
if (completeSudoku(SudokuArray, row, col + 1)) return 1;
else SudokuArray[row][col] = 0;
}
else if ((row + 1)<9)
{
if (completeSudoku(SudokuArray, row + 1, 0)) return 1;
else SudokuArray[row][col] = 0;
}
else return true; //changing 1 to true and true to 1 to get the hang of it
}
}
}
return 0;
}
else return 1;
}
int main()
{
//Declaring arrays
int i, j;
// 0 means unassigned cells
int SudokuArray[9][9] = { { 0, 0, 0, 0, 0, 0, 0, 9, 0 },
{ 1, 9, 0, 4, 7, 0, 6, 0, 8 },
{ 0, 5, 2, 8, 1, 9, 4, 0, 7 },
{ 2, 0, 0, 0, 4, 8, 0, 0, 0 },
{ 0, 0, 9, 0, 0, 0, 5, 0, 0 },
{ 0, 0, 0, 7, 5, 0, 0, 0, 9 },
{ 9, 0, 7, 3, 6, 4, 1, 8, 0 },
{ 5, 0, 6, 0, 8, 1, 0, 7, 4 },
{ 0, 8, 0, 0, 0, 0, 0, 0, 0 } };
//Outputting it
if (completeSudoku(SudokuArray, 0, 0))
{
cout << "\n|-----|-----|-----|\n";
for (i = 1; i<10; ++i)
{
for (j = 1; j<10; ++j)
cout << " " << SudokuArray[i - 1][j - 1];
cout << "|\n";
if (i % 3 == 0)
cout << "|-----|-----|-----|\n";
}
}
else cout << ("\n\nThere is no solution for those numbers!\n\n");
cin.ignore();
cin.get();
return 0;
}
|