几个关键函数和变量解释一下
board :棋盘 , 1 - 9 表示填入的数字 ,0 表示没有填数字
index : 传入 x 和 y , 返回 board 中对应的位置
dump : 打印当前棋盘
getValid : 传入 x 和 y,返回对应位置可填入的合法的数字. 1 - 9 排除同行同列的数字 ,再排除所在3*3区域的数字
resu : 传入 board 中开始检查的位置 , 依次将合法数字填入 ,保证当前位置的前面所有数字都是合法的, 再递归检查下一个位置 . 直到所有格子都填好了,就返回
export class sudo {
static Test() {
let board = [
0, 2, 0, 0, 0, 8, 0, 9, 0,
0, 0, 0, 4, 9, 0, 5, 0, 0,
0, 9, 3, 1, 0, 0, 8, 0, 0,
0, 0, 0, 0, 8, 2, 0, 0, 0,
0, 0, 0, 5, 0, 0, 1, 6, 8,
0, 0, 0, 6, 1, 0, 2, 0, 7,
0, 0, 8, 0, 0, 0, 0, 1, 3,
9, 0, 6, 0, 0, 1, 0, 8, 0,
0, 5, 1, 8, 0, 0, 0, 0, 0
]
sudo.GetResult(board)
}
static GetResult(board: number[]) {
let index = (x, y) => {
return x + y * 9
}
let dump = () => {
let str = ""
for (let j = 0; j < 9; j++) {
for (let i = 0; i < 9; i++) {
str += board[index(i, j)]
}
str += "\n"
}
console.log("\n\n")
console.log(str)
}
let getValid = (x, y) => {
let ret = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let ind = -1
for (let i = 0; i < 9; i++) {
ind = ret.indexOf(board[index(i, y)])
if (ind != -1)
ret.splice(ind, 1)
}
for (let j = 0; j < 9; j++) {
ind = ret.indexOf(board[index(x, j)])
if (ind != -1)
ret.splice(ind, 1)
}
let areaX = Math.floor(x / 3)
let areaY = Math.floor(y / 3)
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
ind = ret.indexOf(board[index(i + areaX * 3, j + areaY * 3)])
if (ind != -1)
ret.splice(ind, 1)
}
}
return ret
}
let loopTimes = 0
let resu = (ind) => {
loopTimes++
let y = ind % 9
let x = (ind - y) / 9
if (ind >= 81)
return true
if (board[index(x, y)] != 0)
return resu(ind + 1)
let validNums = getValid(x, y)
for (let i = 0; i < validNums.length; i++) {
let n = validNums[i]
board[index(x, y)] = n
if (resu(ind + 1) == true)
return true
else
board[index(x, y)] = 0
}
}
dump()
resu(0)
dump()
console.log("loopTimes : " + loopTimes)
return board
}
}