Skip to content

Commit

Permalink
other solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
Azureki committed May 24, 2019
1 parent 2434c4a commit 88c18d1
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 37. Sudoku Solver/0ms.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
func solveSudoku(board [][]byte) {
var marks [9][27]bool
for row := range board {
for col := range board[row] {
num := board[row][col]
if num == '.' {
continue
}
marks[num-49][row], marks[num-49][9+col], marks[num-49][18+row/3*3+col/3] = true, true, true
}
}
sudoku(board, marks, 0, 0)
}

func sudoku(board [][]byte, marks [9][27]bool, row, col int) bool {
if row == len(board) {
return true
}
if board[row][col] != '.' {
return sudoku(board, marks, row+(col+1)/9, (col+1)%9)
}

for num := 1; num <= 9; num++ {
if marks[num-1][row] || marks[num-1][9+col] || marks[num-1][18+row/3*3+col/3] {
continue
}
board[row][col] = byte(num + 48)
marks[num-1][row], marks[num-1][9+col], marks[num-1][18+row/3*3+col/3] = true, true, true
if sudoku(board, marks, row+(col+1)/9, (col+1)%9) {
return true
}
board[row][col] = '.'
marks[num-1][row], marks[num-1][9+col], marks[num-1][18+row/3*3+col/3] = false, false, false
}
return false
}
40 changes: 40 additions & 0 deletions 37. Sudoku Solver/4ms.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
func solveSudoku(board [][]byte) {
solve(board, 0)
}

func solve(board [][]byte, k int) bool {
if k == 81 {
return true
}

r, c := k/9, k%9

if board[r][c] != '.' {
return solve(board, k+1)
}

bi, bj := r/3*3, c/3*3

isValid := func(b byte) bool {
for n := 0; n < 9; n++ {
if board[r][n] == b ||
board[n][c] == b ||
board[bi+n/3][bj+n%3] == b {
return false
}
}
return true
}

for b := byte('1'); b <= '9'; b++ {
if isValid(b) {
board[r][c] = b
if solve(board, k+1) {
return true
}
}
}

board[r][c] = '.'
return false
}
6 changes: 6 additions & 0 deletions 37. Sudoku Solver/README.org
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#+TITLE: Sudoku Solver

我的解法看起来就很杂乱。
4ms 的用一个 k,好很多。而且效率也是一样的。使用 dfs 和递归。

0ms 的没看懂(

0 comments on commit 88c18d1

Please sign in to comment.