TypeScript 解数独

几个关键函数和变量解释一下

board 	:棋盘 , 1 - 9 表示填入的数字 ,0 表示没有填数字
index	: 传入 x 和 y , 返回 board 中对应的位置
dump    : 打印当前棋盘
getValid : 传入 x 和 y,返回对应位置可填入的合法的数字. 1 - 9 排除同行同列的数字 ,再排除所在3*3区域的数字
resu	 : 传入 board 中开始检查的位置 ,  依次将合法数字填入 ,保证当前位置的前面所有数字都是合法的, 再递归检查下一个位置 . 直到所有格子都填好了,就返回
// 可以直接调用 sudo.Test
// 也可以传参调用 sudo.GetResult 
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
        // dump()
        if (resu(ind + 1) == true)
          return true
        else
          board[index(x, y)] = 0
      }
    }
    dump()
    resu(0)
    dump()
    console.log("loopTimes : " + loopTimes)
    return board
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值