Leetcode专题[数组]-36-有效的数独

力扣链接:https://leetcode-cn.com/probl...
解题思路:

  1. 这道题的解法是朴素遍历
  2. 首先遍历每一行是否有重复
  3. 其次遍历每一列是否有重复
  4. 遍历33的格子是否有重复
func isValidSudoku(board [][]byte) bool {
    for i := 0; i < len(board); i++ {
        for j := 0; j < len(board[i]); j++ {
            if i % 3 == 0 && j % 3 == 0 && !isValidSquare(board, i, j) {
                return false
            }
            if !isValidXY(board, i, j) {
                return false
            }
        }
    }
    return true
}

func isValidSquare(board [][]byte, x, y int) bool {
     m := map[byte]bool{}
     for i := x; i < x + 3; i++ {
         for j := y; j < y + 3; j++ {
             if board[i][j] == '.' {
                 continue
             }
             if m[board[i][j]] {
                 return false
             }
             m[board[i][j]] = true
         }
     }
     return true
}

func isValidXY(board [][]byte, x, y int) bool {
    mx := make(map[byte]bool)
    for i := 0; i < 9; i++ {
        if board[x][i] == '.' {
            continue
        }
        if mx[board[x][i]] {
            return false
        }
        mx[board[x][i]] = true
    }
    my := make(map[byte]bool)
    for j := 0; j < 9; j++ {
        if board[j][y] == '.' {
            continue
        }
        if my[board[j][y]] {
            return false
        }
        my[board[j][y]] = true
    }
    return true
}

你可能感兴趣的:(golang)