leetcode-36 Valid Sudoku

来源:互联网 发布:网络娱乐平台 编辑:程序博客网 时间:2024/06/11 20:19

问题描述:

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

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

A partially filled sudoku which is valid.

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

 

问题分析:

判断该数独中的元素是否合法(并不要求将数独解出来);

数独合法意味着:每一行填满1-9;每一列填满1-9;每一个sub子块(3X3)填满1-9

 

只要满足上面三个条件即为合法数独,可以简单地想到使用三个9*9的boolean二维数组,来分别记录每一行,每一列,每一个sub子块中数字的使用情况;遍历数独,当出现重复使用情况,即为不合法;

 

代码:

public class Solution {   public boolean isValidSudoku(char[][] board) {        boolean[][] used1 = new boolean[9][9], // 记录每一行每个数字的使用情况                    used2 = new boolean[9][9], // 记录每一列每个数字的使用情况                used3 = new boolean[9][9]; // 记录每一个sub子块中每个数字的使用情况        // 直接进行遍历即可    for (int i = 0; i < board.length; ++i) {        for (int j = 0; j <board[i].length; ++j) {            if (board[i][j] != '.') {                // 将对应的数字转化为boolean数组对应的位置                int num = board[i][j] - '0' - 1;                // 转化为sub子块所对应的行;由于每一行(3列)需要转化为3行boolean,故需要乘以3                int k   =i / 3 * 3 + j / 3;                // 发现该数字已经使用过,则一定是不合法的                if (used1[i][num] || used2[j][num] ||used3[k][num])                    return false;                // 将已经使用的数字进行标记                used1[i][num] = used2[j][num] =used3[k][num] = true;            }        }    }    return true;   }}


0 0