38. Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

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

A partially filled sudoku which is valid.

 

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

实现题.

public class Solution {
  public boolean isValidSudoku(char[][] board) {
    for (int i = 0; i < 9; i++) {
      boolean[] rows = new boolean[10];
      boolean[] cols = new boolean[10];
      for (int j = 0; j < 9; j++) {
        // Check row
        if (board[i][j] != '.') {
          int n = board[i][j] - '0';
          if (rows[n]) return false;
          rows[n] = true;
        }
        // Check col
        if (board[j][i] != '.') {
          int n = board[j][i] - '0';
          if (cols[n]) return false;
          cols[n] = true;
        }
      }
    }
    // Check subbox
    for (int i = 0; i < 9; i += 3) {
      for (int j = 0; j < 9; j += 3) {
        boolean[] nums = new boolean[10];
        for (int m = 0; m < 3; m++) {
          for (int n = 0; n < 3; n++) {
            if (board[i + m][j + n] != '.') {
              int k = board[i + m][j + n] - '0';
              if (nums[k]) return false;
              nums[k] = true;
            }
          }
        }
      }
    }
    return true;
  }
}

posted on 2015-06-04 09:08  shini  阅读(130)  评论(0编辑  收藏  举报

导航