0036. Valid Sudoku (M)

Valid Sudoku (M)

题目

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.

A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Example 1:

Input:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: true

Example 2:

Input:
[
  ["8","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being 
    modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
  • The given board contain only digits 1-9 and the character '.'.
  • The given board size is always 9x9.

题意

判断一个数独中已经填入的数字是否有效。

思路

直接对每一个数字判断是否有效,可以直接实现,也可以借助hash实现。


代码实现

Java

无hash

class Solution {
    public boolean isValidSudoku(char[][] board) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c != '.' && !isValid(board, i, j, c)) {
                    return false;
                }
            }
        }

        return true;
    }
    
    private boolean isValid(char[][] board, int i, int j, char c) {
        for (int k = 0; k < 9; k++) {
            // 注意要排除自身
            if (k != j && c == board[i][k] || k != i && c == board[k][j]) {
                return false;
            }
        }
		
        // x、y的初始值为对应九宫格左上顶点的坐标
        for (int x = 3 * (i / 3); x < 3 * (i / 3) + 3; x++) {
            for (int y = 3 * (j / 3); y < 3 * (j / 3) + 3; y++) {
                // 注意要排除自身
                if (c == board[x][y] && x != i && y != j) {
                    return false;
                }
            }
        }

        return true;
    }
}

hash

class Solution {
    public boolean isValidSudoku(char[][] board) {
        List<Set<Character>> row = new ArrayList<>();
        List<Set<Character>> col = new ArrayList<>();
        List<Set<Character>> nine = new ArrayList<>();

        for (int i = 0; i < 9; i++) {
            row.add(new HashSet<>());
            col.add(new HashSet<>());
            nine.add(new HashSet<>());
        }

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c != '.') {
                    if (!row.get(i).add(c)) {
                        return false;
                    }
                    if (!col.get(j).add(c)) {
                        return false;
                    }
                    // 九宫格序号的计算公式为 3 * (i / 3) + j / 3
                    if (!nine.get(3 * (i / 3) + j / 3).add(c)) {
                        return false;
                    }
                }
            }
        }

        return true;
    }
}

JavaScript

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function (board) {
  let row = new Array(9).fill(0).map(v => new Set())
  let col = new Array(9).fill(0).map(v => new Set())
  let box = new Array(9).fill(0).map(v => new Set())

  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      let c = board[i][j]
      let boxIndex = Math.trunc(i / 3) * 3 + Math.trunc(j / 3)
      if (c !== '.') {
        if (row[i].has(c) || col[j].has(c) || box[boxIndex].has(c)) {
          return false
        }
        row[i].add(c)
        col[j].add(c)
        box[boxIndex].add(c)
      }
    }
  }

  return true
}

猜你喜欢

转载自www.cnblogs.com/mapoos/p/13193706.html