Leet Code 36 Valid Sudoku - 有效数独 - Java

问题原始链接 https://leetcode.com/problems/valid-sudoku

判断一个部分填写的数独是否有效,没有填写数字的格子中的字符为'.'。

对每一行、每一列、每个小九宫格判断已填写的数字是否有重复。

public class Solution {

  public static boolean isValidSudoku(char[][] board) {
    Set<Character> set = new HashSet<Character>();
    return allRowsValid(board, set) && allColsValid(board, set)
        && squaresValid(board, set);
  }

  private static boolean squaresValid(char[][] board, Set<Character> set) {
    for (int i = 0; i < board.length; i += 3) {
      for (int j = 0; j < board.length; j += 3) {
        if (!isSquarValid(board, i, j, set)) {
          return false;
        }
      }
    }
    return true;
  }

  private static boolean isSquarValid(char[][] board, int i, int j,
      Set<Character> set) {
    for (int r = 0; r < 3; r++) {
      for (int c = 0; c < 3; c++) {
        int a = i + r;
        int b = j + c;

        if (board[a][b] != '.') {
          if (set.contains(board[a][b])) {
            return false;
          } else {
            set.add(board[a][b]);
          }
        }
      }
    }
    set.clear();
    return true;
  }

  private static boolean allColsValid(char[][] board, Set<Character> set) {
    for (int i = 0; i < board.length; i++) {
      for (int j = 0; j < board.length; j++) {
        if (board[j][i] != '.') {
          if (set.contains(board[j][i])) {
            return false;
          } else {
            set.add(board[j][i]);
          }
        }
      }
      set.clear();
    }
    return true;
  }

  private static boolean allRowsValid(char[][] board, Set<Character> set) {
    for (int i = 0; i < board.length; i++) {
      if (!isValidRow(board, i, set)) {
        return false;
      }
    }
    return true;
  }

  private static boolean isValidRow(char[][] board, int row, Set<Character> set) {
    for (int i = 0; i < board[row].length; i++) {
      if (board[row][i] != '.') {
        if (set.contains(board[row][i])) {
          return false;
        } else {
          set.add(board[row][i]);
        }
      }
    }
    set.clear();
    return true;
  }
}

 

转载于:https://my.oschina.net/mistymarch/blog/698663

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值