forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudoku.js
More file actions
Latest commit
77 lines (66 loc) · 2.05 KB
/
Copy pathSudoku.js
File metadata and controls
77 lines (66 loc) · 2.05 KB
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
classSudoku{
// Sudoku Class to hold the board and related functions
constructor(board){
this.board=board
}
findEmptyCell(){
// Find a empty cell in the board (returns [-1, -1] if all cells are filled)
for(leti=0;i<9;i++){
for(letj=0;j<9;j++){
if(this.board[i][j]===0)return[i,j]
}
}
return[-1,-1]
}
check([y,x],value){
// checks if the value to be added in the board is an acceptable value for the cell
// checking through the row
for(leti=0;i<9;i++){
if(this.board[i][x]===value)returnfalse
}
// checking through the column
for(leti=0;i<9;i++){
if(this.board[y][i]===value)returnfalse
}
// checking through the 3x3 block of the cell
constsecRow=Math.floor(y/3)
constsecCol=Math.floor(x/3)
for(leti=(secRow*3);i<((secRow*3)+3);i++){
for(letj=(secCol*3);j<((secCol*3)+3);j++){
if(y!==i&&x!==j&&this.board[i][j]===value)returnfalse
}
}
returntrue
}
solve(){
const[y,x]=this.findEmptyCell()
// checking if the board is complete
if(y===-1&&x===-1)returntrue
for(letval=1;val<10;val++){
if(this.check([y,x],val)){
this.board[y][x]=val
if(this.solve())returntrue
// backtracking if the board cannot be solved using current configuration
this.board[y][x]=0
}
}
// returning false the board cannot be solved using current configuration
returnfalse
}
getSection(row,[start,end]){
returnthis.board[row].slice(start,end)
}
printBoard(output=(...v)=>console.log(...v)){
// helper function to display board
for(leti=0;i<9;i++){
if(i%3===0&&i!==0){
output('- - - - - - - - - - - -')
}
output(
...this.getSection(i,[0,3]),' | ',
...this.getSection(i,[3,6]),' | ',
...this.getSection(i,[6,9]))
}
}
}
export{Sudoku}