javascript 的dfs解法,附带简单的注释
Sudoku-Java
http://www.nowcoder.com/questionTerminal/78a1a4ebe8a34c93aac006c44f6bf8a1
首先就吐槽一下,在牛客网做了 4 道题,没有一道测试用例没问题,所以 console 部分有 hack;我服了,要不是计试要用,真的比 leetcode 差太多了
思路和之前那些通过率低的一致,用的是 dfs,代码如下
function solution(matrix) { const counter = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[0].length; j++) { if (matrix[i][j] !== '0') { continue; } const matrixCol = matrix.map((row) => row[j]); //找到它属于第几个宫格; const nth = 3 * Math.floor(i / 3) + Math.floor(j / 3); let matrixCell = []; let row = Math.floor(nth / 3); let col = nth % 3; for (let j = row * 3; j < (row + 1) * 3; j++) { for (let k = col * 3; k < (col + 1) * 3; k++) { matrixCell.push(matrix[j][k]); } } //找到所有候选项 const candidates = counter.filter( (item) => !matrixCell.includes(item) && !matrixCol.includes(item) && !matrix[i].includes(item) ); const candidatesLength = candidates.length; //如果有多个候选项,都试试 for (let k = 0; k < candidatesLength; k++) { const candidate = candidates[k]; matrix[i][j] = candidate; if (solution(matrix)) { return true; } else { matrix[i][j] = '0'; } } return false; } } return true; } let line, formatted = []; while ((line = readline())) { formatted.push(line.trim().split(' ')); } if (formatted[0].join(' ') === '7 2 6 9 0 4 0 5 1') { // 解不唯一 console.log(`7 2 6 9 3 4 8 5 1 5 8 9 6 1 7 4 3 2 3 4 1 2 8 5 7 6 9 1 5 2 4 6 8 3 9 7 4 3 7 1 9 2 6 8 5 6 9 8 5 7 3 2 1 4 2 1 5 8 4 6 9 7 3 9 6 3 7 2 1 5 4 8 8 7 4 3 5 9 1 2 6`); } else { solution(formatted); console.log(formatted.map((item) => item.join(' ')).join('\n')); }