广度优先遍历-走迷宫

    经常会遇到走迷宫的问题,也就是求一个人从迷宫的起点到终点的任意一条最短路径。

    迷宫可以用二维数组进行表示,1表示可以行走,0表示不能行走。如下所示

         1 0 0 1 1 0

         1 1 1 1 0 1

         0 1 0 1 1 1

         0 0 1 1 0 1

,问题也就是求从左上角到右下角的最短路径。

    典型的广度优先遍历,直接上代码(借鉴别人的,然后进行了简化,更方便学习和理解)

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * @author lishunpu
 * @create 2017-08-26 10:23
 */
public class Main {
    public static String path="";
    public static Deque<String> queue = new LinkedList<String>();
    public static int m, n; //m表示横坐标,y表示纵坐标

    public static void main(String[] args) {
        int[][] map = {
                {1,0,0,1,1,0},
                {1,1,1,1,0,1},
                {0,1,0,1,1,1},
                {0,0,1,1,0,1}
        };
        m = map.length;
        n = map[0].length;
        bfs(0, 0, map);
        System.out.println(path);
    }

    public static void bfs(int x, int y, int[][] map) {
        if (x < 0 || y < 0 || x >= m || y >= n || map[x][y] == 0) {
            return;
        }

        queue.offerLast("[" + x + "," + y + "]"); //将当前位置放入队列中
        map[x][y] = 0; //并将其设置为已经走过

        if (x == m - 1 && y == n - 1) { //到达终点
            updatePath();
            map[x][y] = 1;
            queue.removeLast();
            return;
        }

        bfs(x, y + 1, map); //上
        bfs(x + 1, y, map); //右
        bfs(x, y - 1, map); //下
        bfs(x - 1, y, map); //左
        map[x][y] = 1;
        queue.removeLast();
    }

    public static void updatePath() {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iterator = queue.iterator();
        while (iterator.hasNext())
            sb.append(iterator.next() + ",");
        if (sb.length() > 0)
            sb.deleteCharAt(sb.length() - 1);
        path = sb.toString();
    }
}

    对于上面的输入,结果为 [0,0],[1,0],[1,1],[1,2],[1,3],[2,3],[2,4],[2,5],[3,5]

    题目的变种很多,但主要思想都不会变。

温馨提示:如果要多次求路径,则前后两次会出现不一样的结果,因为每次遍历都会对矩阵中的值进行修改。此时可以新建一个矩阵visit[][],所有值初始化为1,表示没有访问过,用0表示访问过,每次遍历时判断visit[x][y]的值。另外,静态变量不能赋初值(除非能确定在整个遍历过程中其值都不会发生改变),必须在每次查找路径时重新赋值,不信的话可以试试附上的bfs的第一题。

附上遇到的bfs的题:

    http://acm.nyist.net/JudgeOnline/problem.php?pid=58

转载于:https://my.oschina.net/yitiaoxianyu/blog/1524183

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值