Java小實例——實現回溯策略

問題:

迷宮問題:起始是迷宮的左上角(0,0),目的位置是迷宮的右下角(6,12)。其中1代表通道,0代表牆壁。只允許進行垂直或者水平移動,禁止對角線移動。

例子:

1 1 1 0 1 1 0 0 0 1 1 1 1 
1 0 1 1 1 0 1 1 1 1 1 0 1 
1 0 0 0 1 0 1 0 1 0 1 0 1 
1 0 0 0 1 1 1 0 1 0 1 1 1 
1 1 1 1 1 0 0 0 0 1 0 0 0 
0 0 0 0 1 0 0 0 0 0 0 0 0 
0 0 0 0 1 1 1 1 1 1 1 1 1 

分析:

從(0,0)開始往上下左右試探:

  1. 如果選擇的位置是目的位置,成功結束。
  2. 如果選擇的位置是有效位置,但不是目的位置,以此位置繼續上下左右試探下去。
  3. 沒有一個有效位置,說明無法到達 目的位置。

代碼編寫:

Position類:位置類

Maze:迷宮處理類

MazeIterator:自定義迭代類,遍歷上下左右相鄰點  

package com.kzl.backtrack;

/**
 * 位置類
 */
public class Position {

    private int row;
    private int column;

    public Position() {
        row = 0;
        column = 0;
    }

    public Position(int row, int column) {
        this.row = row;
        this.column = column;
    }

    public int getRow() {
        return row;
    }

    public int getColumn() {
        return column;
    }


}
package com.kzl.backtrack;

import java.util.Iterator;

public class Maze {

    private static final byte WALL = 0; // 牆
    private static final byte CORRIDOR = 1; // 通道
    private static final byte PATH = 9; // 路徑通過的位置
    private static final byte TRIED = 2; // 死衚衕

    public Position finish;

    public byte[][] grid;

    public Maze(byte[][] grid, Position finish) {
        this.grid = grid;
        this.finish = finish;
    }

    // 判斷位置是否有效
    public boolean valid(Position pos) {
        if (pos.getRow() >= 0 && pos.getRow() < grid.length &&
                pos.getColumn() >= 0 && pos.getColumn() < grid[0].length &&
                grid[pos.getRow()][pos.getColumn()] == CORRIDOR) {
            return true;
        }
        return false;
    }

    // 記錄路徑通過的位置
    public void record(Position pos) {
        grid[pos.getRow()][pos.getColumn()] = PATH;
    }

    // 判斷是否到達目的地
    public boolean done(Position pos) {
        return pos.getRow() == finish.getRow() &&
                pos.getColumn() == finish.getColumn();
    }

    // 如果走不通,就回退,並把此位置置爲死衚衕
    public void undo(Position pos) {
        grid[pos.getRow()][pos.getColumn()] = TRIED;
    }

    // 自定義迭代方法
    public Iterator iterator(Position pos) {
        return new MazeIterator(pos);
    }

    // 回溯策略的主要步驟
    public boolean tryToSolve(Position pos) {
        boolean success = false;
        Iterator it = iterator(pos);
        // 沒有到達目的地,在這個位置的上下左右試探
        while (!success && it.hasNext()) {
            pos = (Position)it.next();
            // 如果該位置有效
            if (valid(pos)) {
                // 記錄該位置
                record(pos);
                // 如果是目的地,結束
                if (done(pos)) {
                    success = true;
                } else {
                    // 如果是有效位置,但不是目的地,繼續調用tryToSolve方法
                    success = tryToSolve(pos);
                    // 如果走不通
                    if (!success) {
                        // 該位置爲死衚衕
                        undo(pos);
                    }
                }
            }
        }

        return success;
    }
}
package com.kzl.backtrack;

import java.util.Iterator;

public class MazeIterator implements Iterator {

    private int row;
    private int column;
    private int count = 0;

    public MazeIterator(Position pos) {
        this.row = pos.getRow();
        this.column = pos.getColumn();
    }

    @Override
    public boolean hasNext() {
        return count < 4;
    }

    @Override
    public Object next() {
        Position next = null;
        // 遍歷4個方向
        switch (count++) {
            case 0:
                next = new Position(row - 1, column);
                break;
            case 1:
                next = new Position(row, column - 1);
                break;
            case 2:
                next = new Position(row + 1, column);
                break;
            case 3:
                next = new Position(row, column + 1);
        }
        return next;
    }

    @Override
    public void remove() {

    }

}
package com.kzl.backtrack;

public class Main {

    public static void main(String[] args) {

        byte[][] grid = {
                {1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1},
                {1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1},
                {1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1},
                {1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1},
                {1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0},
                {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        };

        Position start = new Position();
        Position finish = new Position(6, 12);

        process(grid, start, finish);
    }


    public static void process(byte[][] grid, Position start, Position finish) {
        Maze maze = new Maze(grid, finish);
        if (!maze.valid(start) || !(maze.valid(finish))) {
            System.out.println("failure");
        } else {
            maze.record(start);
            if (maze.done(start) || maze.tryToSolve(start)) {
                System.out.println("success");
            } else {
                maze.undo(start);
                System.out.println("failure");
            }
        }

        for (byte[] b : grid) {
            for (byte t : b) {
                System.out.print(t + " ");
            }
            System.out.println();
        }
    }
}

結果截圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章