SUDOKU Game Code - PROLOG and C++
Sudoku is a logic-based, number-placement puzzle. In this game, the target is to fill a 9×9 grid with numbers from 1 to 9.
Rules to fill it are:-
1. Every Row should be having exactly one occurrence of all 9 digits(1 to 9).
2. Every Column should be having exactly one occurrence of all 9 digits(1 to 9).
3. Every diagonal should be having exactly one occurrence of all 9 digits(1 to 9).
4. Each of the nine 3 × 3 subgrids that compose the grid (also called "boxes", "blocks", or "regions") contain all of the digits from 1 to 9.
The puzzle setter provides a partially completed grid, which for a well-posed puzzle has a single solution.
For example,
Problem setter will give you this:-
And Solution to this would be:-
Algorithm:
- Create a function that checks if the given matrix is valid sudoku or not. Keep Hashmap for the row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true;
- Create a recursive function that takes a grid and the current row and column index.
- Check some base cases. If the index is at the end of the matrix, i.e. i=N-1 and j=N then check if the grid is safe or not, if safe print the grid and return true else return false. The other base case is when the value of column is N, i.e j = N, then move to next row, i.e. i++ and j = 0.
- if the current index is not assigned then fill the element from 1 to 9 and recur for all 9 cases with the index of next element, i.e. i, j+1. if the recursive call returns true then break the loop and return true.
- if the current index is assigned then call the recursive function with index of next element, i.e. i, j+1
Code in C++ :-
Code in PROLOG:-
% render solutions nicely.
:- use_rendering(sudoku).
:- use_module(library(clpfd)).
% Example by Markus Triska, taken from the SWI-Prolog manual.
sudoku(Rows) :-
length(Rows, 9), maplist(same_length(Rows), Rows),
append(Rows, Vs), Vs ins 1..9,
maplist(all_distinct, Rows),
transpose(Rows, Columns),
maplist(all_distinct, Columns),
Rows = [A,B,C,D,E,F,G,H,I],
blocks(A, B, C), blocks(D, E, F), blocks(G, H, I).
blocks([], [], []).
blocks([A,B,C|Bs1], [D,E,F|Bs2], [G,H,I|Bs3]) :-
all_distinct([A,B,C,D,E,F,G,H,I]),
blocks(Bs1, Bs2, Bs3).
problem(1, [[_,_,_, _,_,_, _,_,_],
[_,_,_, _,_,3, _,8,5],
[_,_,1, _,2,_, _,_,_],
[_,_,_, 5,_,7, _,_,_],
[_,_,4, _,_,_, 1,_,_],
[_,9,_, _,_,_, _,_,_],
[5,_,_, _,_,_, _,7,3],
[_,_,2, _,1,_, _,_,_],
[_,_,_, _,4,_, _,_,9]]).
/** <examples>
?- problem(1, Rows), sudoku(Rows).
*/
ConversionConversion EmoticonEmoticon