Leetcode - Longest Harmonious Subsequence
Leetcode - Reveal Cards In Increasing Order

Leetcode - Valid Sudoku

violet posted @ 5 年前 in 算法 with tags Algorithm Golang hash , 355 阅读

https://leetcode.com/problems/valid-sudoku/

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
func isValidSudoku(board [][]byte) bool {
    hash := map[byte]bool{}
    for i := 0; i < 9; i++ {
        hash = map[byte]bool{}
        for j := 0; j < 9; j++ {
            if board[i][j] != '.' {
                if hash[board[i][j]] {
                    return false
                }
                hash[board[i][j]] = true
            }
        }
         
    }
     
    for j := 0; j < 9; j++ {
        hash = map[byte]bool{}
        for i := 0; i < 9; i++ {
            if board[i][j] != '.' {
                if hash[board[i][j]] {
                    return false
                }
                hash[board[i][j]] = true
            }
        }
         
    }
    for i := 0; i < 9; i += 3{
        for j := 0; j < 9; j += 3 {
            if !checkBox(board, i, j) {
                return false
            }
        }
    }
     
    return true
}
 
func checkBox(board [][]byte, m, n int) bool {
    hash := map[byte]bool{}
    for i := m; i < m + 3; i++ {
        for j := n; j < n + 3; j++ {
            if board[i][j] != '.' {
                if hash[board[i][j]] {
                    return false
                }
                hash[board[i][j]] = true
            }
        }
    }
     
    return true
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter