public class kkkk {
public static void main(String[] args) {
int a[] ={1,2,3,4,6};
int target=6;
/++i 和i++ 魔吐,先相加后返回的區(qū)別,在此處其實(shí)效果都一樣/
twoSum(a,target);
System.out.println("------");
twoSuma(a,target);
char[][] board = {
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}
};
// 三個(gè)布爾數(shù)組 表明 行, 列, 還有 33 的方格的數(shù)字是否被使用過
boolean[][] rowUsed = new boolean[9][10];
boolean[][] colUsed = new boolean[9][10];
boolean[][][] boxUsed = new boolean[3][3][10];
// 初始化
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board[0].length; col++) {
int num = board[row][col] - '0';
if(1 <= num && num <= 9){
rowUsed[row][num] = true;
colUsed[col][num] = true;
boxUsed[row/3][col/3][num] = true;
}
}
}
// 遞歸嘗試填充數(shù)組
recusiveSolveSudoku(board, rowUsed, colUsed, boxUsed, 0, 0);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
if(j==8){
System.out.println("------");
}
}
}
System.out.println();
}
public static boolean recusiveSolveSudoku(char[][]board, boolean[][]rowUsed, boolean[][]colUsed, boolean[][][]boxUsed, int row, int col){
// 邊界校驗(yàn), 如果已經(jīng)填充完成, 返回true, 表示一切結(jié)束
if(col == board[0].length){
col = 0;
row++;
if(row == board.length){
return true;
}
}
// 是空則嘗試填充, 否則跳過繼續(xù)嘗試填充下一個(gè)位置
if(board[row][col] == '.') {
// 嘗試填充1~9
for(int num = 1; num <= 9; num++){
boolean canUsed = !(rowUsed[row][num] || colUsed[col][num] || boxUsed[row/3][col/3][num]);
if(canUsed){
rowUsed[row][num] = true;
colUsed[col][num] = true;
boxUsed[row/3][col/3][num] = true;
board[row][col] = (char)('0' + num);
if(recusiveSolveSudoku(board, rowUsed, colUsed, boxUsed, row, col + 1)){
return true;
}
board[row][col] = '.';
rowUsed[row][num] = false;
colUsed[col][num] = false;
boxUsed[row/3][col/3][num] = false;
}
}
} else {
return recusiveSolveSudoku(board, rowUsed, colUsed, boxUsed, row, col + 1);
}
return false;
}
/**數(shù)組中找出兩個(gè)數(shù)和為指定數(shù)值*/
public static int[] twoSum(int[] nums, int target) {
int numa=nums.length;
for (int i = 0; i < numa; ++i) {
for (int j = i+1; j < numa; ++j) {
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return new int[0];
}
public static int[] twoSuma(int[] nums, int target) {
int numa=nums.length;
for (int i = 0; i < numa; i++) {
for (int j = i+1; j < numa; j++) {
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return new int[0];
}
}