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]);
    				}
    			}
    			
    		}
    	}
    }
    
    
    多思考,多尝试。
  • 相关阅读:
    再看机器学习
    普通MLP处理图像时遇到了什么样的问题,才导致后续各种模型的出现
    图像分类算法为什么有那么多?
    算法的时间复杂度到底怎么算?
    [Python]7种基础排序算法-Python实现
    [Python3]星号*的打开方式
    [Pyspark]RDD常用方法总结
    [Python3]为什么map比for循环快
    Sass简介
    最全的DOM事件笔记
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9474087.html
Copyright © 2011-2022 走看看