迷宫伪代码和8皇后问题源代码
讲解见视频
迷宫的伪代码
Maze map = ...; // 地图初始化
Position target = ...; // 目标位置
List<Position> findCandidates(Position last, Position current) {
// 根据当前位置找可能的选择
}
Path find(Position pos, Path path)
{
if(pos.equals(target)) {
return path.concat(target);
}
var candidates = findCandidates(path.last(), pos);
for(var candidate : candidates) {
// 确保每个状态空间的数据独立
var newPath = path.clone();
newPath.add(pos);
var p = find(pos, newPath);
if(p != null) {
return p;
}
}
return null;
}
八皇后问题源代码
package datastructure;
import java.util.Arrays;
public class EQueen {
int[] queens = new int[8];
public boolean solve(int col) {
if(col == 8) {
return true;
}
// i : row
for(int i = 0; i < 8; i++) {
queens[col] = i;
boolean flag = true;
for(int j = 0; j < col; j++) {
var rowDiff = Math.abs(queens[j] - i);
var colDiff = col - j;
if(queens[j] == i || rowDiff == colDiff) {
flag = false;
break;
}
}
if(flag && solve(col + 1)) {
return true;
}
}
return false;
}
void print(){
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
if(queens[i] == j) {
System.out.print("Q");
} else {
System.out.print(".");
}
}
System.out.print("\n");
}
}
public static void main(String[] argv) {
var equeen = new EQueen();
equeen.solve(0);
equeen.print();
}
}