您的位置:首页 > 其它

LeetCode 笔记系列十 Suduko

2013-07-07 18:27 731 查看
题目: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.

下面是一个数独的题目:

/**
* 决定board[row][col]可填写的数字
* @param board
* @param row
* @param col
* @param set 当函数返回时,set[i]为false表明数字i+1可以填写到棋盘中。
* @return
*/
private static boolean[] scanColRowGrid(char[][] board, int row, int col, boolean[] set){
for(int i = 0; i < SIZE; i++){
if(board[row][i] >= '1' && board[row][i] <= '9') {
set[board[row][i] - '1'] = true;
}
}
for(int i = 0; i < SIZE; i++){
if(board[i][col] >= '1' && board[i][col] <= '9') {
set[board[i][col] - '1'] = true;
}
}
int grid = getGrid(row, col);
int st_row = 3 * (grid / 3);
int st_col = 3 * (grid % 3);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
char c = board[st_row + i][st_col + j];
if(c >= '1' && c <= '9') {
set[c - '1'] = true;
}
}
}
return set;
}

/**
* 通过行号和列号查询该格子所在的3x3格
* @param row
* @param col
* @return 0~8的数字,代表从左到右从上到下的3x3格标号
*/
private static int getGrid(int row, int col){
return 3 * (row / 3) + col / 3;
}


View Code
注意我们对3x3格的标号方式,是从左到右从上到下,标号为0~8,方便我们转换。

这道题虽然不难,但是比较经典,值得总结。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: