zoukankan      html  css  js  c++  java
  • 图的广度优先遍历(BFS)

    使用邻接矩阵进行存储
    原图

    调整后

    package graph;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    
    public class BFSTraverse {
    	private static ArrayList<Integer> list = new ArrayList<Integer>();
    	// 邻接矩阵存储;
    	public static void main(String[] args) {
    		// 初始数据;
    		int[] vertexs = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
    		int[][] edges = { { 0, 1, 0, 0, 0, 1, 0, 0, 0 }, { 1, 0, 1, 0, 0, 0, 1, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 0, 1 },
    				{ 0, 0, 1, 0, 1, 0, 1, 1, 1 }, { 0, 0, 0, 1, 0, 1, 0, 1, 0 }, { 1, 0, 0, 0, 1, 0, 1, 0, 0 },
    				{ 0, 1, 0, 1, 0, 1, 0, 1, 0 }, { 0, 0, 0, 1, 1, 0, 1, 0, 0 }, { 0, 1, 1, 1, 0, 0, 0, 0, 0 } };
    		BFSTraverse(vertexs, edges);
    		System.out.println("深度遍历结果:" + list);
    
    	}
    	private static void BFSTraverse(int[] vertexs,int[][] edges) {
    		boolean[] visited = new boolean[vertexs.length];
    		for(int i=0;i<visited.length;i++) {
    			visited[i]=false;
    		}
    		LinkedList<Integer> helper=new LinkedList<Integer>();//辅助队列;
    		helper.offerLast(vertexs[0]);//将第一个放入访问队列;
    		visited[0]=true;
    		BFS(vertexs,edges,visited,helper);
    	}
    	private static void BFS(int[] vertexs,int[][] edges,boolean[] visited,LinkedList<Integer> helper) {
    		while(!helper.isEmpty()) {
    			int i = helper.pollFirst();
    			
    			list.add(i);
    			for(int j=0;j<vertexs.length;j++) {
    				if(edges[i][j]==1&&!visited[j]) {
    					visited[j]= true; //注意这个放置的位置,应该是将顶点放入到队列的时候进行设置,不能再将顶点从队列取出的时候再设置;
    					helper.offerLast(vertexs[j]);
    				}
    			}
    			
    		}
    	}
    }
    
    
    多思考,多尝试。
  • 相关阅读:
    PHPCMS V9后台表单向导用户提交的信息新增“修改”的功能
    phpcms V9最实用的23个调用代码
    phpcms V9推荐位无法调用自定义字段的解决方法
    将博客搬至CSDN
    爬取淘宝商品信息selenium+pyquery+mongodb
    selenium库
    requests库+ajax数据分析+多线程爬取头条图集
    requests微博爬取Ajax数据+mongoDB存储
    redis存储
    pymongo操作MongoDB
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9474087.html
Copyright © 2011-2022 走看看