• 图的广度优先遍历(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]);
    				}
    			}
    			
    		}
    	}
    }
    
    
    多思考,多尝试。
  • 相关阅读:
    sql试题
    sql中的游标
    SQL Server存储过程 对数组参数的循环处理
    MongoDB安装并随windows开机自启
    延长或控制Session的有效期的方法总结
    回忆我们经典的开发工具(转)
    多线程实例,占用CPU过多
    啥叫单例模式?
    判断字符或字符串里是否有汉字
    百年历19552055年
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9474087.html
Copyright © 2020-2023  润新知