package Algorithm;
import java.awt.*;
import java.util.ArrayList;
import java.util.Comparator;
public class HorseAlgorithm {
private static int X;//棋盘的行数
private static int Y;//棋盘的列数
private static boolean [] isVisited;
private static boolean isFinished;
public static void main(String[] args) {
X = 8;
Y = 8;
int row = 1;
int column = 1;
int [][] chessboard = new int[X][Y];
isVisited = new boolean[X * Y];
long start = System.currentTimeMillis();
travelChessboard(chessboard,row - 1, column - 1, 1);
long end = System.currentTimeMillis();
System.out.println("花了" + (end - start) + "毫秒");
//输出结果(走法)
for(int [] rows : chessboard){
for(int step : rows){
System.out.print(step + " ");
}
System.out.println();
}
}
/**
*
* @param chessboard 棋盘
* @param row 马儿当前的位置所在的行
* @param column 马儿当前的位置所在的列
* @param step 是第几步,初始化为 1
*/
public static void travelChessboard(int [][] chessboard, int row, int column, int step){
chessboard[row][column] = step;//记录步数
isVisited[row * Y + column] = true;//标志已经访问
ArrayList<Point> ps = next(new Point(row,column));
//优化,对ps进行非递减排序
sort(ps);
//遍历当前位置所有可以走的下一步
while (!ps.isEmpty()) {
Point p = ps.remove(0);//取出下一个可走的位置
//判断是否访问过
if(!isVisited[p.x * Y + p.y]){//没有访问过
travelChessboard(chessboard,p.x,p.y,step + 1);
}
}
//表示未走完棋盘或者没有解
//此时,回溯
if( step < X * Y && !isFinished ) {
chessboard[row][column] = 0;
isVisited[row * Y + column] = false;
} else {
isFinished = true;//退出
}
}
public static ArrayList<Point> next(Point curPoint){
Point p1 = new Point();
ArrayList<Point> ps = new ArrayList<>();
//判断马儿还能走哪个位置
//往左2步,向上一步走日
if(( p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y - 1) >= 0 ){
ps.add(new Point(p1));
}
//往左1步,向上2步走日
if( (p1.x = curPoint.x - 1) >= 0 && (p1.y = curPoint.y - 2) >= 0 ){
ps.add(new Point(p1));
}
//往右1步,向上2步走日
if( (p1.x = curPoint.x + 1) < Y && (p1.y = curPoint.y - 2) >= 0 ){
ps.add(new Point(p1));
}
//往右2步,向上1步走日
if((p1.x = curPoint.x + 2) < Y && (p1.y = curPoint.y - 1) >= 0 ){
ps.add(new Point(p1));
}
//往右2步,向下1步走日
if((p1.x = curPoint.x + 2) < Y && (p1.y = curPoint.y + 1) < X ){
ps.add(new Point(p1));
}
//往右一步,向下2步走日
if((p1.x = curPoint.x + 1) < Y && (p1.y = curPoint.y + 2) < X ){
ps.add(new Point(p1));
}
//往左一步,向下两步走日
if((p1.x = curPoint.x - 1) >= 0 && (p1.y = curPoint.y + 2) < X ){
ps.add(new Point(p1));
}
//往左两步,向下一步走日
if((p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y + 1) < X ){
ps.add(new Point(p1));
}
return ps;
}
//使用贪心算法进行优化:
//1.获取当前位置的下一个可以走的所有位置的集合ps
//2.对ps中所有的Point进行非递减排序
//1 2 2 2 3 4 5 6 -->非递减
//根据当前这一步的所有下一步的选择位置,进行非递减排序
public static void sort(ArrayList<Point> ps){
ps.sort(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
//获取o1的下一步的所有位置
int count1 = next(o1).size();
//获取o2的下一步的所有位置
int count2 = next(o2).size();
if(count1 < count2){
return -1;
} else if (count1 == count2){
return 0;
} else {
return 1;
}
}
});
}
}
骑士周游问题、马踏棋盘算法的实现及使用贪心算法进行优化代码实现
最新推荐文章于 2024-04-12 01:18:11 发布