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

Leetcode - Valid Sudoku

violet posted @ Apr 17, 2020 06:34:56 AM in 算法 with tags Algorithm Golang hash , 329 阅读

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.

 

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