From 5374fb48a4ebacd714cb74ae979a5fd09a4c7f28 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 4 Apr 2022 21:41:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880037.=E8=A7=A3?= =?UTF-8?q?=E6=95=B0=E7=8B=AC.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0037.解数独.md | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index 53b9bb67..c1ac15af 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -439,6 +439,55 @@ var solveSudoku = function(board) { }; ``` +### TypeScript + +```typescript +/** + Do not return anything, modify board in-place instead. + */ +function isValid(col: number, row: number, val: string, board: string[][]): boolean { + let n: number = board.length; + // 列向检查 + for (let rowIndex = 0; rowIndex < n; rowIndex++) { + if (board[rowIndex][col] === val) return false; + } + // 横向检查 + for (let colIndex = 0; colIndex < n; colIndex++) { + if (board[row][colIndex] === val) return false; + } + // 九宫格检查 + const startX = Math.floor(col / 3) * 3; + const startY = Math.floor(row / 3) * 3; + for (let rowIndex = startY; rowIndex < startY + 3; rowIndex++) { + for (let colIndex = startX; colIndex < startX + 3; colIndex++) { + if (board[rowIndex][colIndex] === val) return false; + } + } + return true; +} +function solveSudoku(board: string[][]): void { + let n: number = 9; + backTracking(n, board); + function backTracking(n: number, board: string[][]): boolean { + for (let row = 0; row < n; row++) { + for (let col = 0; col < n; col++) { + if (board[row][col] === '.') { + for (let i = 1; i <= n; i++) { + if (isValid(col, row, String(i), board)) { + board[row][col] = String(i); + if (backTracking(n, board) === true) return true; + board[row][col] = '.'; + } + } + return false; + } + } + } + return true; + } +}; +``` + ### C ```C