LeetCode 37.解数独
问题描述
编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
数字 1-9 在每一行只能出现一次。数字 1-9 在每一列只能出现一次。数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
空白格用 ‘.’ 表示。
一个数独。
答案被标成红色。
Note:
给定的数独序列只包含数字 1-9 和字符 ‘.’ 。你可以假设给定的数独只有唯一解。给定数独永远是 9x9 形式的。
题目分析
看到题目我们很容易地想到应该要用回溯算法来解答此题,对此我们需要一个检查位置的函数来判断当前位置能否填写某一数字。之后遍历每个位置,试着将1~9填入每个位置,直到填满整个9宫格结束遍历。
小九宫格下标:
代码
var columns
= [],
rows
= [],
grids
= [],
f
= 0;
var init = function(board
){
for (let i
= 0; i
< 9; i
++) {
for (let j
= 0; j
< 9; j
++) {
const value
= board
[i
][j
];
if (value
!== '.') {
rows
[i
].push(value
);
columns
[j
].push(value
);
const gridIndex
= Math
.floor(i
/ 3) * 3 + Math
.floor(j
/ 3);
grids
[gridIndex
].push(value
);
}
}
}
};
var check = function(i
,j
,board
,value
){
const gridIndex
= Math
.floor(i
/ 3) * 3 + Math
.floor(j
/ 3);
if (rows
[i
].includes(value
) || columns
[j
].includes(value
) || grids
[gridIndex
].includes(value
)) {
return false;
}
return true;
};
var fillBoard = function(i
,j
,board
){
if(f
== 1 || i
> 8) {
return ;
}
if(board
[i
][j
] == '.'){
for(let num
= 1; num
< 10; num
++){
if(f
== 0 && check(i
,j
,board
,num
.toString())){
rows
[i
].push(num
.toString());
columns
[j
].push(num
.toString());
const gridIndex
= Math
.floor(i
/ 3) * 3 + Math
.floor(j
/ 3);
grids
[gridIndex
].push(num
.toString());
board
[i
][j
] = num
.toString();
if(i
== 8 && j
== 8) {
f
= 1;
return;
}else if(j
== 8) fillBoard(i
+ 1,0,board
);
else fillBoard(i
,j
+1,board
);
if(f
== 0){
rows
[i
].pop();
columns
[j
].pop();
grids
[gridIndex
].pop();
board
[i
][j
] = '.';
}
}
}
}else if(i
== 8 && j
== 8) {
f
= 1;
return;
}else if(j
== 8) fillBoard(i
+ 1,0,board
);
else fillBoard(i
,j
+1,board
);
return board
;
};
var solveSudoku = function(board
) {
f
= 0;
for(let i
= 0; i
< 9; i
++){
columns
[i
] = [];
rows
[i
] = [];
grids
[i
] = [];
}
init(board
);
board
= fillBoard(0,0,board
);
};
其他
个人博客:http://kscccisu.cn:8090/