題目:
編寫一個程序,通過已填充的空格來解決數獨問題。
一個數獨的解法需遵循如下規則:
數字 1-9 在每一行只能出現一次。
數字 1-9 在每一列只能出現一次。
數字 1-9 在每一個以粗實線分隔的 3x3 宮內只能出現一次。
空白格用 '.' 表示。
一個數獨。
答案被標成紅色。
Note:
給定的數獨序列只包含數字 1-9 和字符 '.' 。
你可以假設給定的數獨只有唯一解。
給定數獨永遠是 9x9 形式的。
思路:
先將已有的數字信息進行按行/列/3*3宮格保存,並保存爲空的格子位置信息
然後使用遞歸策略,從左至右、從上到下對空數據的格子進行填充
填充規則:若符合數字規則則繼續進行下一個數字的填充,若無法滿足條件,則返回到上一個數字的填充
代碼:
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solveSudoku = function (board) {
var i, j, columns = [], rows = [], grids = [], spaces = [], success = false;
for (i = 0; i < board.length; i++) {
columns.push({});
rows.push({});
grids.push({});
}
for (i = 0; i < board.length; i++) {
for (j = 0; j < board[i].length; j++) {
if (board[i][j] == ".") {
spaces.push([i, j]);
continue;
}
rows[i][board[i][j]] = '1';
columns[j][board[i][j]] = '1';
grids[Math.floor(i / 3) * 3 + Math.floor(j / 3)][board[i][j]] = '1';
}
}
function insertNum(index) {
if (index >= spaces.length) {
success = true;
return;
}
var i, row = spaces[index][0], column = spaces[index][1], grid = Math.floor(spaces[index][0] / 3) * 3 + Math.floor(spaces[index][1] / 3);
for (var i = 1; i <= 9; i++) {
if (rows[row][i] == null && columns[column][i] == null && grids[grid][i] == null) {
board[row][column] = i + '';
rows[row][i] = '1';
columns[column][i] = '1';
grids[grid][i] = '1';
insertNum(index + 1);
if (success) {
return;
}
board[row][column] = '.';
rows[row][i] = null;
columns[column][i] = null;
grids[grid][i] = null
}
}
}
insertNum(0);
console.log(board);
};
代碼地址:github地址