您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Sudoku Solver

2015-06-06 16:43 711 查看

Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character
'.'
.

You may assume that there will be only one unique solution.



A sudoku puzzle...



...and its solution numbers marked in red.

https://leetcode.com/problems/sudoku-solver/

又是一道DFS。

test case比较弱,只有6个,并且说好了都是可解的。

每到一格先看看是不是结束了或者不需要填,否则调用findCandidate方法找出在当前这一步所有可填的数字,然后开始递归。

递归的时候就按照顺序,先横着走,走到底了换一行。

每一轮递归回来都要把默认的'.'写回去,否则会影响下一轮的结果。

开了个flag记录是不是结束,如果已经遍历完就return掉,不用再找了。

/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solveSudoku = function(board) {
var isComplete = false;
dfs(0, 0);

function dfs(x, y){
if(isComplete){
return;
}
var candidates = findCandidate(x, y);
if(x === 8 && y == 8){
if(board[8][8] === '.'){
board[8][8] = candidates[0];
}
isComplete = true;
return;
}

if(board[x][y] !== '.'){
if(y === 8){
dfs(x + 1, 0);
return;
}else{
dfs(x, y + 1);
return;
}
}
for(var i = 0; i < candidates.length; i++){
board[x][y] = candidates[i];
if(y === 8){
dfs(x + 1, 0);
}else{
dfs(x, y + 1);
}
if(!isComplete){
board[x][y] = '.';
}else{
return;
}
}
}

function findCandidate(x, y){
var set = new Set();
var candidate = [];
var cell = -1;
//row
for(i = 0; i < 9; i++){
cell = board[x][i];
if(!set.has(cell)){
set.add(cell);
}
}
//column
for(i = 0; i < 9; i++){
cell = board[i][y];
if(!set.has(cell)){
set.add(cell);
}
}
//square
var offsetX = parseInt(x / 3) * 3;
var offsetY = parseInt(y / 3) * 3;
for(i = 0; i <= 2; i++){
for(j = 0; j <= 2; j++){
cell = board[i + offsetX][j + offsetY];
if(!set.has(cell)){
set.add(cell);
}
}
}
//find candidate
for(i = 1; i <= 9; i++){
if(!set.has(i + "")){
candidate.push(i + "");
}
}
return candidate;
}
};


附赠一个UT

function test(){
var map = [
['5','3','.','.','7','.','.','.','.'],
['6','.','.','1','9','5','.','.','.'],
['.','9','8','.','.','.','.','6','.'],
['8','.','.','.','6','.','.','.','3'],
['4','.','.','8','.','3','.','.','1'],
['7','.','.','.','2','.','.','.','6'],
['.','6','.','.','.','.','2','8','.'],
['.','.','.','4','1','9','.','.','5'],
['.','.','.','.','8','.','.','7','9']
]

solveSudoku(map);

for(var m = 0; m < map.length; m++){
var line = "";
for(var n = 0; n < map[m].length; n++){
line += (map[m]
+ ",");
}
console.log(line);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: