Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0cadf6a

Browse files
committedJan 18, 2023
Add solution #37
1 parent 08711bc commit 0cadf6a

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium|
4343
35|[Search Insert Position](./0035-search-insert-position.js)|Easy|
4444
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
45+
37|[Sudoku Solver](./0037-sudoku-solver.js)|Hard|
4546
38|[Count and Say](./0038-count-and-say.js)|Medium|
4647
39|[Combination Sum](./0039-combination-sum.js)|Medium|
4748
40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium|

‎solutions/0037-sudoku-solver.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 37. Sudoku Solver
3+
* https://leetcode.com/problems/sudoku-solver/
4+
* Difficulty: Hard
5+
*
6+
* Write a program to solve a Sudoku puzzle by filling the empty cells.
7+
*
8+
* A sudoku solution must satisfy all of the following rules:
9+
* - Each of the digits 1-9 must occur exactly once in each row.
10+
* - Each of the digits 1-9 must occur exactly once in each column.
11+
* - Each of the digits 1-9 must occur exactly once in each of the
12+
* 9 3x3 sub-boxes of the grid.
13+
* - The '.' character indicates empty cells.
14+
*/
15+
16+
/**
17+
* @param {character[][]} board
18+
* @return {void} Do not return anything, modify board in-place instead.
19+
*/
20+
var solveSudoku = function(board) {
21+
for (let i = 0; i < board.length; i++) {
22+
for (let j = 0; j < board.length; j++) {
23+
if (board[i][j] === '.') {
24+
for (let k = 1; k < 10; k++) {
25+
if (isValid(board, i, j, k.toString())) {
26+
board[i][j] = k.toString();
27+
const solution = solveSudoku(board);
28+
if (solution !== false) {
29+
return solution;
30+
}
31+
board[i][j] = '.';
32+
}
33+
}
34+
return false;
35+
}
36+
}
37+
}
38+
39+
return board;
40+
};
41+
42+
function isValid(board, i, j, k) {
43+
for (let index = 0; index < board.length; index++) {
44+
if (board[i][index] === k) return false;
45+
if (board[index][j] === k) return false;
46+
const [x, y] = [
47+
3 * Math.floor(i / 3) + Math.floor(index / 3),
48+
3 * Math.floor(j / 3) + index % 3,
49+
];
50+
if (board[x][y] === k) {
51+
return false;
52+
}
53+
}
54+
55+
return true;
56+
}

0 commit comments

Comments
 (0)
Please sign in to comment.