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 ‘.’.
public class Solution {
public boolean isValidSudoku(char[][] board) {
if(board==null || board.length==0 || board[0].length==0)return true;
int m=board.length, n=board[0].length;
HashSet<Character> row=new HashSet<Character>();
ArrayList<HashSet<Character>> column=new ArrayList<HashSet<Character>>();
ArrayList<HashSet<Character>> block=new ArrayList<HashSet<Character>>();
for(int i=0;i<n;i++)column.add(new HashSet<Character>() );
for(int i=0;i<m*n/9;i++)block.add(new HashSet<Character>());
for(int i=0;i<m;i++)
{
row.clear();
for(int j=0;j<n;j++)
{
if( board[i][j]=='.' )continue;
if( row.contains(board[i][j]) )return false;
else row.add(board[i][j]);
if( column.get(j).contains(board[i][j]) )return false;
else column.get(j).add(board[i][j]);
if( block.get(i/3*(n/3)+j/3).contains(board[i][j]) )return false;
else block.get(i/3*(n/3)+j/3).add(board[i][j]);
}
}
return true;
}
}
[Thoughts]’
空间换时间
Sudoku solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character ‘.’.
You may assume that there will be only one unique solution.
[code]
public class Solution {
ArrayList<HashSet<Character>> row=new ArrayList<HashSet<Character>>();
ArrayList<HashSet<Character>> column=new ArrayList<HashSet<Character>>();
ArrayList<HashSet<Character>> block=new ArrayList<HashSet<Character>>();
public void solveSudoku(char[][] board) {
if(board==null || board.length==0 || board[0].length==0)return;
int m=board.length, n=board[0].length;
for(int i=0;i<m;i++)row.add(new HashSet<Character>() );
for(int i=0;i<n;i++)column.add(new HashSet<Character>() );
for(int i=0;i<m*n/9;i++)block.add(new HashSet<Character>());
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(board[i][j]!='.')
{
row.get(i).add(board[i][j]);
column.get(j).add(board[i][j]);
block.get( (i/3)*(n/3)+j/3 ).add(board[i][j]);
}
}
}
solve(board, 0, 0);
}
boolean solve(char[][] board, int r, int col)
{
int m=board.length, n=board[0].length;
if(r==m)return true;
if(board[r][col]!='.')
{
return col==n-1 ? solve(board, r+1, 0) : solve(board, r, col+1);
}
else
{
for(char i='1';i<='9';i++)
{
if( row.get(r).contains(i) )continue;
if( column.get(col).contains(i)) continue;
if( block.get( (r/3)*(n/3)+col/3 ).contains(i) )continue;
row.get(r).add(i);
column.get(col).add(i);
block.get( (r/3)*(n/3)+col/3 ).add(i);
board[r][col]=i;
boolean result= col==n-1 ? solve(board, r+1, 0) : solve(board, r, col+1);
if(result)return true;
row.get(r).remove(i);
column.get(col).remove(i);
block.get( (r/3)*(n/3)+col/3 ).remove(i);
board[r][col]='.';
}
return false;
}
}
}
[Thoughts]
index mapping容易出错,最好举例子测一下