骑士周游(dfs+greedy)

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。骑士周游(dfs+greedy),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

骑士周游(DFS+Greedy):

提示:马踏棋盘问题 也称 骑士周游问题

记录一道dfs+greedy的题目,
这道题能够帮助我们更好的理解dfs中的优化问题


题目描述:

提示:马踏棋盘问题(骑士周游问题)实际上是图的深度优先搜索(DFS)的应用。

如果使用回溯(就是深度优先搜索)来解决,假如马儿踏了53个点,如图:走到了第53个,坐标1,0),发现已经走到尽头,没办法,那就只能回退了,查看其他的路径,就在棋盘上不停的回溯……

在这里插入图片描述

解决步骤及思路:

骑士周游问题:

  • 1.创建棋盘chessBoard ,是一个二维数组

  • 2.将当前位置设置为已经访问,然后根据当前位置,计算马儿还能走哪些位置,并放入到一个集合中(Arraylist),最多有8个位置,每走一步,就使用step+1。

  • 3.遍历ArrayList中存放的所有位置,看看哪个可以走通,如果走通,就继续,走不通,就回溯.

  • 4.判断马儿是否完成了任务,使用step和应该走的步数比较,如果没有达到数量,则表示没有完成任务,将整个棋盘置0

其实我们仔细思考后会发现问题,这样的想法会产生很多回溯,必然严重超时,我们应该在每次选择中,用贪心算法( greedyalgorithm)进行优化,选择最少路的先走!

使用贪心算法对原来的算法优化

  1. 我们获取当前位置,可以走的下一个位置的集合//获取当前位置可以走的下一个位置的集合 ArrayList ps =next(new point(column, row));
  2. 我们需要对ps 中所有的Point的下一步的所有集合的数目,进行非递减排序,就ok!
9,7,6,5,3,2, 1 //递增排序
1,2,3,4,5,6,10 //递增排序
12,2,2,3,3,4,5,6 //非递减
0,7.6.6.6.5.53,2,1 //非递增

代码实现:

提示:详细解释请看注释

import java.awt.Point;
import java.util.ArrayList;
import java.util.Comparator;

public class HorseChessboard {

	private static int X; // 棋盘的列数
	private static int Y; // 棋盘的行数
	//创建一个数组,标记棋盘的各个位置是否被访问过
	private static boolean[] visited;
	//使用一个属性,标记是否棋盘的所有位置都被访问
	private static boolean finished; // 如果为true,表示成功

	public static void main(String[] args) {
		System.out.println("骑士周游算法,开始运行~~");
		//测试骑士周游算法是否正确
		X = 8;
		Y = 8;
		int row = 1; //马儿初始位置的行,从1开始编号
		int column = 1; //马儿初始位置的列,从1开始编号
		//创建棋盘
		int[][] chessboard = new int[X][Y];
		visited = new boolean[X * Y];//初始值都是false
		//测试一下耗时
		long start = System.currentTimeMillis();
		dfs(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 + "\t");
			}
			System.out.println();
		}
	}
	
	/**
	 * 完成骑士周游问题的算法
	 * @param chessboard 棋盘
	 * @param row 马儿当前的位置的行 从0开始 
	 * @param column 马儿当前的位置的列  从0开始
	 * @param step 是第几步 ,初始位置就是第1步 
	 */
	public static void dfs(int[][] chessboard, int row, int column, int step) {
		chessboard[row][column] = step;
		//这里是把二维数组降维为一维数组,通过加上前面的行数和当前的列数,得到现在是第几个元素
		visited[row * X + column] = true; //标记该位置已经访问
		//获取当前位置可以走的下一个位置的集合
//-----------不能把这个list写在外面!每次递归都需要一个单独的list对象,表示每层递归中下一次可以走的点的集合
		ArrayList<Point> ps = next(new Point(column, row));
		//对ps进行排序,排序的规则就是对ps的所有的Point对象的下一步的位置的数目,进行非递减排序
//-----------下面这句话是贪心的体现,并且要注意:
// ---------------不要直接在这里面写比较器,因为每次创建并且执行这样的操作,也会花费时间,单独写一个方法来比较,用空间换时间
		sort(ps);
		//遍历 ps
		while(!ps.isEmpty()) {
			Point p = ps.remove(0);//取出下一个可以走的位置
			//判断该点是否已经访问过
//-----------这里把x 看成列,y 看成行,模拟坐标中的(x,y)
			if(!visited[p.y * X + p.x]) {//说明还没有访问过
				dfs(chessboard, p.y, p.x, step + 1);
			}
		}
		//判断马儿是否完成了任务,使用   step 和应该走的步数比较 , 
		//如果没有达到数量,则表示没有完成任务,将整个棋盘置0
		//说明: step < X * Y  成立的情况有两种
		//1. 棋盘到目前位置,仍然没有走完
		//2. 棋盘处于一个回溯过程
//-----------这里是回溯的过程,和普通的dfs一样,从每次dfs的最深处开始回溯,如果没有走完,把状态重置,以免影响下一次的递归
		if(step < X * Y && !finished ) {
			chessboard[row][column] = 0;
			visited[row * X + column] = false;
		} else {
			finished = true;
		}
		
	}
	
	/**
	 * 功能: 根据当前位置(Point对象),计算马儿还能走哪些位置(Point),并放入到一个集合中(ArrayList), 最多有8个位置
	 * @param curPoint
	 * @return
	 */
	public static ArrayList<Point> next(Point curPoint) {
		//创建一个ArrayList
		ArrayList<Point> ps = new ArrayList<>();
		//创建一个Point
		Point p1 = new Point();
		//表示马儿可以走5这个位置
		if((p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y -1) >= 0) {
			ps.add(new Point(p1));
		}
		//判断马儿可以走6这个位置
		if((p1.x = curPoint.x - 1) >=0 && (p1.y=curPoint.y-2)>=0) {
			ps.add(new Point(p1));
		}
		//判断马儿可以走7这个位置
		if ((p1.x = curPoint.x + 1) < X && (p1.y = curPoint.y - 2) >= 0) {
			ps.add(new Point(p1));
		}
		//判断马儿可以走0这个位置
		if ((p1.x = curPoint.x + 2) < X && (p1.y = curPoint.y - 1) >= 0) {
			ps.add(new Point(p1));
		}
		//判断马儿可以走1这个位置
		if ((p1.x = curPoint.x + 2) < X && (p1.y = curPoint.y + 1) < Y) {
			ps.add(new Point(p1));
		}
		//判断马儿可以走2这个位置
		if ((p1.x = curPoint.x + 1) < X && (p1.y = curPoint.y + 2) < Y) {
			ps.add(new Point(p1));
		}
		//判断马儿可以走3这个位置
		if ((p1.x = curPoint.x - 1) >= 0 && (p1.y = curPoint.y + 2) < Y) {
			ps.add(new Point(p1));
		}
		//判断马儿可以走4这个位置
		if ((p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y + 1) < Y) {
			ps.add(new Point(p1));
		}
		return ps;
	}

	//根据当前这个一步的所有的下一步的选择位置,进行非递减排序, 减少回溯的次数
	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;
				}
			}
			
		});
	}
}


精简版代码:

import java.awt.*;
import java.util.ArrayList;
import java.util.Comparator;

public class HorseChessboardSimple {

    private static int X;
    private static int Y;
    private static boolean[] visited;
    private static boolean isFinished;

    public static void main(String[] args) {
        X = 8;
        Y = 8;
        int[][] chessboard = new int[X][Y];
        visited = new boolean[X * Y];
        dfs(chessboard, 0, 0, 1);
        for (int[] rows : chessboard) {
            for (int step : rows)
                System.out.print(step + "\t");
            System.out.println();
        }
    }

    public static void dfs(int[][] chessboard, int row, int column, int step) {
        chessboard[row][column] = step;
        visited[row * X + column] = true;
        ArrayList<Point> ps = next(new Point(column, row));
        sort(ps);
        while (!ps.isEmpty()) {
            Point p = ps.remove(0);
            if (!visited[p.y * X + p.x])
                dfs(chessboard, p.y, p.x, step + 1);
        }
        if (step < X * Y && !isFinished) {
            chessboard[row][column] = 0;
            visited[row * X + column] = false;
        } else
            isFinished = true;
    }

    public static ArrayList<Point> next(Point curPoint) {
        ArrayList<Point> ps = new ArrayList<>();
        Point p1 = new Point();
        if ((p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y - 1) >= 0) ps.add(new Point(p1));

        if ((p1.x = curPoint.x - 1) >= 0 && (p1.y = curPoint.y - 2) >= 0) ps.add(new Point(p1));

        if ((p1.x = curPoint.x + 1) < X && (p1.y = curPoint.y - 2) >= 0) ps.add(new Point(p1));

        if ((p1.x = curPoint.x + 2) < X && (p1.y = curPoint.y - 1) >= 0) ps.add(new Point(p1));

        if ((p1.x = curPoint.x + 2) < X && (p1.y = curPoint.y + 1) < Y) ps.add(new Point(p1));

        if ((p1.x = curPoint.x + 1) < X && (p1.y = curPoint.y + 2) < Y) ps.add(new Point(p1));

        if ((p1.x = curPoint.x - 1) >= 0 && (p1.y = curPoint.y + 2) < Y) ps.add(new Point(p1));

        if ((p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y + 1) < Y) ps.add(new Point(p1));

        return ps;
    }

    public static void sort(ArrayList<Point> ps) {
        ps.sort((o1, o2) -> {
            int count1 = next(o1).size();
            int count2 = next(o2).size();
            return Integer.compare(count1, count2);
        });
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/159833.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!