题目描述
Determine if a Sudoku is valid, according to:
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
解题思路
本题要求判断是否为九宫格。而九宫格为 http://sudoku.com.au/TheRules.aspx。主要就是对二维数组进行操作的练习。
自己的代码
Determine if a Sudoku is valid, according to:
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
解题思路
本题要求判断是否为九宫格。而九宫格为 http://sudoku.com.au/TheRules.aspx。主要就是对二维数组进行操作的练习。
自己的代码
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
//按行比较
for(int i = 0; i < 9; i++){
List<Character> list = new ArrayList<Character>();
for(int j = 0; j < 9; j++){
char cur = board[i][j];
for(char elem : list){
if(elem == cur) return false;
}
if(cur != '.') list.add(cur);
}
}
//按列比较
for(int j = 0; j < 9; j++){
List<Character> list = new ArrayList<Character>();
for(int i = 0; i < 9; i++){
char cur = board[i][j];
for(char elem : list){
if(elem == cur) return false;
}
if(cur != '.') list.add(cur);
}
}
//按九宫格比较
for(int i = 0; i < 9; i = i + 3){
for(int j = 0; j < 9; j = j + 3){
List<Character> list = new ArrayList<Character>();
for(int m = i; m < i + 3; m++){
for(int n = j; n < j + 3; n++){
char cur = board[m][n];
for(char elem : list){
if(elem == cur) return false;
}
if(cur != '.') list.add(cur);
}
}
}
}
return true;
}
public static void main(String[] args) {
char[][] board = {
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'}
};
ValidSudoku vs = new ValidSudoku();
System.out.println(vs.isValidSudoku(board));
}
}