JAVA BFS 广度搜索

来源:互联网 发布:php mvc的实现 编辑:程序博客网 时间:2024/05/29 15:09

今天来记录一下学的广度搜索..

刷segmentfault的时候,发现一个朋友说广度搜索的步骤挺清晰的,其核心步骤就几个:

1:初始结点(入队列),并标记初始结点。

2:判断目前队列是否为空,非空继续,若空则退出。

3:初始结点(出队列),以出队列的这个点搜索它的邻接结点。

4:如果找到邻接结点w,先判断是否已标记,是否出界,是否不合法,之后可行的话,标记w并且  w(入队列)。(判断当前邻接结点是否是我们寻找的点,是的话直接返回。)返回第二步。

5:如果找不到,返回第二步。


一个蓝桥杯的例子(算法提高 学霸的迷宫  ):

问题描述
  学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗。但学霸为了不要别人打扰,住在一个城堡里,城堡外面是一个二维的格子迷宫,要进城堡必须得先通过迷宫。因为班长还有妹子要陪,磨刀不误砍柴功,他为了节约时间,从线人那里搞到了迷宫的地图,准备提前计算最短的路线。可是他现在正向妹子解释这件事情,于是就委托你帮他找一条最短的路线。
输入格式
  第一行两个整数n, m,为迷宫的长宽。
  接下来n行,每行m个数,数之间没有间隔,为0或1中的一个。0表示这个格子可以通过,1表示不可以。假设你现在已经在迷宫坐标(1,1)的地方,即左上角,迷宫的出口在(n,m)。每次移动时只能向上下左右4个方向移动到另外一个可以通过的格子里,每次移动算一步。数据保证(1,1),(n,m)可以通过。
输出格式
  第一行一个数为需要的最少步数K。
  第二行K个字符,每个字符∈{U,D,L,R},分别表示上下左右。如果有多条长度相同的最短路径,选择在此表示方法下字典序最小的一个。
样例输入
Input Sample 1:
3 3
001
100
110

Input Sample 2:
3 3
000
000
000
样例输出
Output Sample 1:
4
RDRD

Output Sample 2:
4
DDRR
数据规模和约定
  有20%的数据满足:1<=n,m<=10
  有50%的数据满足:1<=n,m<=50
  有100%的数据满足:1<=n,m<=500。


解题思路:其实用DFS也可以做一部分,只不过一旦n太大就不行了,并且DFS不能直接得出最短路径,要直接求最短路径还是要用BFS。

public static void main(String args[]){        Scanner in = new Scanner(System.in);        int n = in.nextInt();        int m = in.nextInt();        int [][] a = new int[n][m];        for(int i = 0;i <n;i++){        for(int j=0;j<m;j++)            a[i][j] = in.nextInt();        }        in.close();        bfs(a,m);    }

主方法很简单,只是输入两个数n,m,然后再输入一个数组,接着调用bfs方法。

static void bfs(int [][] a, int m) {       ArrayList<point> list = new ArrayList<point>();       list.add(new point(0,0,0,""));   //表示从顶点(1,1)出发       int minStep = Integer.MAX_VALUE;  //用于记录到达最终顶点所需最少步数       String minPath = "";         //用于记录到达最终顶点路径的最小字典序序列       while(list.size() != 0) {           point begin = list.get(0);  //获取链表第一个顶点,开始进行bfs遍历           list.remove(0);  //删除进行遍历的起始点                      if(begin.x == a.length - 1 && begin.y == a[0].length - 1) {  //当该顶点为终点时               if(minStep > begin.step) {                   minStep = begin.step;                   minPath = begin.path;               } else if(minStep == begin.step) {                    if(judge(minPath, begin.path))  //当minPath字典序大于begin.step时                       minPath = begin.path;               }               continue;   //此处已经是终点,不需要进行下面bfs遍历           }                      for(int i = 0;i < 4;i++) {  //如果未达到最终顶点(n, m),进行bfs遍历(分别向上、下、左、右移动)               int x = begin.x + move[i][0];               int y = begin.y + move[i][1];               int step = begin.step + 1;               String path = begin.path + dire[i] ;               point temp = new point(x, y, step, path);               if(check(a, temp)) {  //当顶点temp是可到达的顶点时                   list.add(temp);                   a[x][y] = 1;  //到达该顶点后,标记该顶点不可到达,此处奥秘是大大减少了检索次数(如果换成其父母顶点不可到达,则会运行超时)               }           }       }       //输出最终结果       System.out.println(minStep+"\n"+minPath);       return;   }
上面是博客园里面 舞动的心 作者的代码(我修改了一部分)。

其实BFS架构可以归纳成以下这样:

1: 创建一个容器。(可以是数组,队列,链表等都可以)

2:把起点放进容器里。(一般是队列,因为要实现先进先出)

3:判断目前容器是否为空,若不是空的 则把容器最先放进去的点取出来。若是,则输出

4:判断取出来的点是否为我们要找的点,若是,则记录当前获取到这个点所经过的路径和步数,返回。若不是则跳到下一步。

5:以取出来的点为主要操作的对象,寻找它的邻接点:,若寻找到,记录邻接点的状态,路径和步数更新到邻接点。

6:判断邻接点是否合法,是的话就把找到的邻接点放进容器。(入队列)

7:标记目前邻接点,跳回第三步。



完整代码:

import java.util.ArrayList;import java.util.Scanner; public class Main{     public final static int[][] move = {{-1, 0},{1,0},{0,-1},{0,1}};        public final static String[] dire = {"U","D","L","R"};        static class point {              public int x;              public int y;              public int step;              public String path;                    point(int x, int y, int step, String path) {                this.x = x;                this.y = y;                this.step = step;                this.path = path;            }        }        //判断当前位置是否是可行走的位置,如不能返回false,否则返回true        static boolean check(int[][] matrix, point a) {            int n = matrix.length - 1, m = matrix[0].length - 1;            if(a.x < 0 || a.x > n || a.y < 0 || a.y > m || matrix[a.x][a.y] == 1)                return false;            return true;        }                //依据字典序{D,L,R,U},比较字符串A和B的大小,如果A > B返回true,否则返回false(PS:两者字符个数相同)        static boolean judge(String A, String B) {            char[] arrayA = A.toCharArray();            char[] arrayB = B.toCharArray();            for(int i = 0, len = A.length();i < len;i++) {                if(arrayA[i] < arrayB[i])                    return false;            }            return true;        }static void bfs(int [][] a, int m) {       ArrayList<point> list = new ArrayList<point>();       list.add(new point(0,0,0,""));   //表示从顶点(1,1)出发       int minStep = Integer.MAX_VALUE;  //用于记录到达最终顶点所需最少步数       String minPath = "";         //用于记录到达最终顶点路径的最小字典序序列       while(list.size() != 0) {           point begin = list.get(0);  //获取链表第一个顶点,开始进行bfs遍历           list.remove(0);  //删除进行遍历的起始点                      if(begin.x == a.length - 1 && begin.y == a[0].length - 1) {  //当该顶点为终点时               if(minStep > begin.step) {                   minStep = begin.step;                   minPath = begin.path;               } else if(minStep == begin.step) {                    if(judge(minPath, begin.path))  //当minPath字典序大于begin.step时                       minPath = begin.path;               }               continue;   //此处已经是终点,不需要进行下面bfs遍历           }                      for(int i = 0;i < 4;i++) {  //如果未达到最终顶点(n, m),进行bfs遍历(分别向上、下、左、右移动)               int x = begin.x + move[i][0];               int y = begin.y + move[i][1];               int step = begin.step + 1;               String path = begin.path + dire[i] ;               point temp = new point(x, y, step, path);               if(check(a, temp)) {  //当顶点temp是可到达的顶点时                   list.add(temp);                   a[x][y] = 1;  //到达该顶点后,标记该顶点不可到达,此处奥秘是大大减少了检索次数(如果换成其父母顶点不可到达,则会运行超时)               }           }       }       //输出最终结果       System.out.println(minStep+"\n"+minPath);       return;   }    public static void main(String args[]){        Scanner in = new Scanner(System.in);        int n = in.nextInt();        int m = in.nextInt();        int [][] a = new int[n][m];        for(int i = 0;i <n;i++){            for(int j=0;j<m;j++)                a[i][j] = in.nextInt();        }        in.close();        bfs(a,m);     }}

上述代码整体框架是参考博客园的舞动的心作者的成果 http://www.cnblogs.com/liuzhen1995/p/6597188.html#commentform

感谢舞动的心的代码..要是有侵权的话..请第一时间告诉我..

0 0
原创粉丝点击