LeetCode:Valid Sudoku

题目链接:Valid Sudoku

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

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

题目大意即:给一个9X9的数独图,判断当前在3X3正方形、行、列中有无重复的数字。

思路就是一遍扫描,并想好位置的映射关系。

代码如下:

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        int[][] counts_row = new int[9][9];
        int[][] counts_square = new int[9][9];
        int[][] counts_column = new int[9][9];
        int number;
        for (int row=0; row<9; row++) {
            for (int column=0; column<9; column++) {
                if (board[row][column] == '.') {
                    continue;
                }
                number = board[row][column]-'0'-1;
                int position = (row/3)*3+column/3;

                if (counts_row[row][number] != 0 || counts_square[position][number] != 0
                        || counts_column[column][number] != 0) {
                    return false;
                } 

                // 行
                counts_row[row][number] = 1;
                // 列
                counts_column[column][number] = 1;
                // 矩形
                counts_square[position][number] = 1;
            }
        }
        return true;
    }    
}
原文地址:https://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/p/12041938.html