程序員常用 10 種算法之馬踏棋盤算法


馬踏棋盤算法

馬踏棋盤算法介紹和游戲演示:

1) 馬踏棋盤算法也被稱為騎士周游問題
2) 將馬隨機放在國際象棋的 8×8 棋盤 Board[0~7][0~7]的某個方格中,馬按走棋規則(馬走日字)進行移動。要求每個方格只進入一次,走遍棋盤上全部 64 個方格
3) 游戲演示: http://www.4399.com/flash/146267_2.htm


馬踏棋盤游戲代碼實現:

1) 馬踏棋盤問題(騎士周游問題)實際上是圖的深度優先搜索(DFS)的應用。
2) 如果使用回溯(就是深度優先搜索)來解決,假如馬兒踏了 53 個點,如圖:走到了第 53 個,坐標(1,0),發現已經走到盡頭,沒辦法,那就只能回退了,查看其他的路徑,就在棋盤上不停的回溯…… , 思路分析+代碼

對第一種實現方式的思路圖解:

3) 分析第一種方式的問題,並使用貪心算法(greedyalgorithm)進行優化。解決馬踏棋盤問題.

4) 使用前面的游戲來驗證算法是否正確。

代碼實現:

package com.pierce.algorithm;

import java.awt.*;
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();
        traversalChessboard(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 traversalChessboard(int[][] chessboard, int row, int column, int step) {
        chessboard[row][column] = step;
        //row = 4 X = 8 column = 4 = 4 * 8 + 4 = 36
        visited[row * X + column] = true; //標記該位置已經訪問
        //獲取當前位置可以走的下一個位置的集合
        ArrayList<Point> ps = next(new Point(column, row));
        //對 ps 進行排序,排序的規則就是對 ps 的所有的 Point 對象的下一步的位置的數目,進行非遞減排序
        sort(ps);
        //遍歷 ps
        while (!ps.isEmpty()) {
            Point p = ps.remove(0);//取出下一個可以走的位置
            //判斷該點是否已經訪問過
            if (!visited[p.y * X + p.x]) {//說明還沒有訪問過
                traversalChessboard(chessboard, p.y, p.x, step + 1);
            }
        }
        //判斷馬兒是否完成了任務,使用 step 和應該走的步數比較 ,
        //如果沒有達到數量,則表示沒有完成任務,將整個棋盤置 0
        //說明: step < X * Y 成立的情況有兩種
        //1. 棋盤到目前位置,仍然沒有走完
        //2. 棋盤處於一個回溯過程
        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
        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) {
                // TODOAuto-generated method stub
                //獲取到 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;
                }
            }
        });
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM