数据结构与算法 27 马踏棋盘 骑士周游 贪心算法优化

马踏棋盘

代码实现思想

实际上是图的深度优先搜索(回溯)

  1. 创建棋盘 chessBoard,是一个二维数组
  2. 将当前位置设置为已经访问,然后根据当前位置,计算马儿还能走那些位置,并放入到一个集合中(ArrayList),最多有8个位置。每走一步,就 step+1
  3. 遍历ArrayList中存放的所有位置,看看哪个可以走通;如果走通,则继续;走不通,就回溯
  4. 判断马是否完成了任务 step 和应该走的步数(整个棋盘的格数-1)比较,如果没有达到数量,则表示没有完成任务,将整个棋盘置0

注意:马不同的走法会得到不同的结果,效率也会有影响(优化)


67
50
🐎
41
32
// 马可以走5这个位置
if((p1.x = curPoint.x-2) >= 0 && (p1.y = curPoint.y - 1) >= 0){
  ps.add(new Point(p1));
}

计算马的位置

visited[row * X + column] = true;
// row = 4 X = 8 column = 4 position = 36
// index start from 0

代码实现

package algorithm.horse;

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

public class HorseChess {

    private static int X; // col of chess
    private static int Y; // row of chess
    // create an array to record whether chess point has been visited
    private static boolean visited[];
    // use a attribute to mark whether all the position has been visited
    private static boolean finished; // success if the result is true

    public static void main(String[] args) {
        X = 8;
        Y = 8;
        int row = 1; // start point of horse, index from 1
        int column = 1; // col of start point of horse
        // create chess board
        int[][] chessboard = new int[X][Y];
        visited = new boolean[X*Y]; // default value is false
        long start = System.currentTimeMillis();
        traversalChess(chessboard,row-1,column-1,1);
        long end = System.currentTimeMillis();
        System.out.println("time cost: "+(end-start)+" ms");
        // print chess board
        for(int[] rows: chessboard){
            for(int val: rows){
                System.out.print(val+"  ");
            }
            System.out.println();
        }
    }

    /**
     * algorithm of horse travel
     * @param chessboard chess board
     * @param row row of horse's position, start from 0
     * @param column col of horse's position, start from 0
     * @param step which step, initial step is 1
     */
    public static void traversalChess(int[][] chessboard,int row,int column,int step){
        chessboard[row][column] = step;
        visited[row*X + column] = true; // mark this position visited
        // get the collection of next positions horse can go for current position
        ArrayList<Point> ps = next(new Point(column, row));
        // traverse ps, find which position can go
        while(!ps.isEmpty()){
            Point p = ps.remove(0); // get next position the horse can go
            // determine if this point has been visited
            if(!visited[p.y * X+p.x]){ // not visited
                traversalChess(chessboard,p.y,p.x,step+1);
            }
        }
        // determine whether finished task, compare num of chessboard and step
        // if not match, not finish the task, reset chess board to 0
        // note: there are two scenario of step<X*Y
        // 1. horse not reach all positions in the chess board
        // 2. chess board is in a trace back status

        if(step<X*Y && !finished){
            chessboard[row][column] = 0; // reset whole chess board ??
            visited[row*X + column] = false;
        } else{
            finished = true;
        }
    }

    /**
     * 根据当前位置(Point对象),计算马还能走那些位置(Point),
     * 并放入到一个集合(ArrayList)中,最多有8个位置
     * @param curPoint
     * @return
     */
    public static ArrayList<Point> next(Point curPoint){
        // create ArrayList
        ArrayList<Point> ps = new ArrayList<Point>();
        // create Point
        Point p1 = new Point();
        // horse can go to point 5
        if((p1.x = curPoint.x-2) >= 0 && (p1.y = curPoint.y - 1) >= 0){
            ps.add(new Point(p1));
        }
        // horse can go to point 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;

    }
}

优化

贪心算法:如果马下一步可以走【5,6,7】,走5的下一步只能走2步,走6的下一步还能走4步,走7的下一步可以走5步,则优先走5

  1. 获取到当前位置,可以走的下一个位置的集合

    ArrayList<Point> ps = next(new Point(column, row));
    
  2. 需要对ps的下一步所有点的下一步进行非递减排序(递减过程中可以有重复的值)

    // num of next step of current step's next steps, sort
        public static void sort(ArrayList<Point> ps){
            ps.sort(new Comparator<Point>() {
                @Override
                public int compare(Point o1, Point o2) {
                    // get num of all next positions of o1
                    int count1 = next(o1).size();
                    int count2 = next(o2).size();
                    if(count1 < count2){
                        return -1;
                    }else if (count1 == count2){
                        return 0;
                    }else{
                        return count1;
                    }
                }
            });
        }
    
    ArrayList<Point> ps = next(new Point(column, row));
    // sort
    sort(ps);
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值