File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {character[][] } board
3
+ * @return {void } Do not return anything, modify board in-place instead.
4
+ */
5
+ const solveSudoku = function ( board ) {
6
+ dfs ( 0 , 0 )
7
+ function dfs ( row , col ) {
8
+ if ( row === 9 ) return true
9
+ if ( col === 9 ) return dfs ( row + 1 , 0 )
10
+ if ( board [ row ] [ col ] === "." ) {
11
+ for ( let num = 1 ; num <= 9 ; num ++ ) {
12
+ if ( isValid ( row , col , `${ num } ` ) ) {
13
+ board [ row ] [ col ] = `${ num } `
14
+ if ( dfs ( row , col + 1 ) ) return true
15
+ board [ row ] [ col ] = "."
16
+ }
17
+ }
18
+ } else {
19
+ return dfs ( row , col + 1 )
20
+ }
21
+ return false
22
+ }
23
+ function isValid ( row , col , num ) {
24
+ for ( let rowIdx = 0 ; rowIdx < 9 ; rowIdx ++ ) if ( board [ rowIdx ] [ col ] === num ) return false
25
+ for ( let colIdx = 0 ; colIdx < 9 ; colIdx ++ ) if ( board [ row ] [ colIdx ] === num ) return false
26
+
27
+ let squareRowStart = row - ( row % 3 )
28
+ let squareColStart = col - ( col % 3 )
29
+ for ( let rIdx = 0 ; rIdx < 3 ; rIdx ++ ) {
30
+ for ( let cIdx = 0 ; cIdx < 3 ; cIdx ++ ) {
31
+ if ( board [ squareRowStart + rIdx ] [ squareColStart + cIdx ] === num ) return false
32
+ }
33
+ }
34
+ return true
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments