1. 云栖社区>
2. >
3. 正文

# 数据结构经典算法学习之八皇后01

```package wj.arithmatic;

public class EQueen {

int now = 0;
public int row;
public int col;
public int equeen[];

// 八皇后图样初始化
public void init() {
for (int i = 1; i < 9; i++) {
for (int j = 1; j < 9; j++) {
if (((i % 2 != 0) && (j % 2 == 0)) || ((i % 2 == 0) && (j % 2 != 0))) {
System.out.print(" ■");
} else {
System.out.print(" □");
}
}
System.out.println();
}
}

// 判定是否被攻击
public boolean isKilled(int row, int col, int[] equeen) {
if (equeen.length != 0) {
// 其实equeen中只存行号，因为每一个正确位置的皇后必然是在紧邻不同列，顾列号可以用i来代替
for (int i = 0; i < equeen.length; i++) {
// 是否同行
if (row == equeen[i]) {
return false;
}
// 是否同列
if (col == i) {
return false;
}
// 是否对角线
if ((row - col) == (equeen[i] - col) || (row + col) == (equeen[i] + col)) {
return false;
}
}
return true;
}
return true;
}

public boolean equeen(int row, int col, int[] equeen) {
boolean b = this.isKilled(row, col, equeen);
if (b) {
equeen[col] = 1;
return true;
}
return false;
}

public void start() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
boolean b = this.equeen(row, col, equeen);
if (b) {
equeen(i, j, equeen);
}
}
}
}

public static void main(String args[]) {
new EQueen().init();
}
}
```

40+云计算产品，6个月免费体验