买房问题# Living
d*c
1 楼
CC里8.8 Write an algorithm to print all ways of arranging eight queens on a
chess board so that none of them share the same row, column or diagonal.
12行 printBoard();什么功能。是类似println();吗?谢谢!
01 int columnForRow[] = new int [8];
02 boolean check(int row) {
03 for (int i = 0; i < row; i++) {
04 int diff = Math.abs(columnForRow[i] - columnForRow[row]);
05 if (diff == 0 || diff == row - i) return false;
06 }
07 return true;
08 }
09
10 void PlaceQueen(int row){
11 if (row == 8) {
12 printBoard();
13 return;
14 }
15 for (int i = 0; i < 8; i++) {
16 columnForRow[row]=i;
17 if(check(row)){
18 PlaceQueen(row+1);
19 }
20 }
21 }
chess board so that none of them share the same row, column or diagonal.
12行 printBoard();什么功能。是类似println();吗?谢谢!
01 int columnForRow[] = new int [8];
02 boolean check(int row) {
03 for (int i = 0; i < row; i++) {
04 int diff = Math.abs(columnForRow[i] - columnForRow[row]);
05 if (diff == 0 || diff == row - i) return false;
06 }
07 return true;
08 }
09
10 void PlaceQueen(int row){
11 if (row == 8) {
12 printBoard();
13 return;
14 }
15 for (int i = 0; i < 8; i++) {
16 columnForRow[row]=i;
17 if(check(row)){
18 PlaceQueen(row+1);
19 }
20 }
21 }