leetcode 37. Sudoku Solver
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 37. Sudoku Solver相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/str' title='str'>str
pre rac javascrip floor code mat UNC OLE濂介毦锛屾病鍑犱釜鏈堝氨蹇樿浜?/p>
function solveSudoku(board) {
var result = []
function backtrack(x, y) {
if (x == 9) { //鎵?鍗版墍鏈? board.forEach(function (row) {
result.push(row.concat())
})
return true
} else {
if (board[x][y] == '.') {
for (var i = 1; i <= 9; i++) {//灏濊瘯鍦ㄦ牸瀛愰噷闈㈠~鍏?-9
if (check(board, x, y, i + '')) {
board[x][y] = i + "" //澶勭悊鎺?
if (backtrack((y == 8 ? x + 1 : x), (y == 8 ? 0 : y + 1))) {
return true
}
}
}
board[x][y] = '.';
} else {
if (backtrack((y == 8 ? x + 1 : x), (y == 8 ? 0 : y + 1))) {
return true
}
}
}
}
function check(board, x, y, k) {
for (var i = 0; i < 9; i++) {
//鎴戜滑鎯冲湪board[x][y] 涓~鍏锛?缁撴灉鍦╞oard[x][i] 鎴?board[i][y] 鍑虹幇鐩稿悓鐨刱
if (board[x][i] == k || board[i][y] == k) {
return false;
}
}
//妫€鏌ヤ節瀹牸
var xx = Math.floor(x / 3)
var yy = Math.floor(y / 3)
for (var i = xx * 3; i < (xx + 1) * 3; i++) {
for (var j = yy * 3; j < (yy + 1) * 3; j++) {
if (board[i][j] == k) {
return false;
}
}
}
return true;
}
backtrack(0, 0)
// console.log(JSON.stringify(result))
return result;
}
以上是关于leetcode 37. Sudoku Solver的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 37. Sudoku Solver —— 解数独
LeetCode 37 Sudoku Solver(求解数独)