(/≧▽≦)/~┴┴ 嗨~我叫小奥 ✨✨✨
👀👀👀 个人博客:小奥的博客
👍👍👍:个人CSDN
⭐️⭐️⭐️:传送门
🍹 本人24应届生一枚,技术和水平有限,如果文章中有不正确的内容,欢迎多多指正!
📜 欢迎点赞收藏关注哟! ❤️
文章目录
- [1. 建图](#1. 建图)
- [2. DFS模板](#2. DFS模板)
- [3. BFS模板](#3. BFS模板)
1. 建图
            
            
              java
              
              
            
          
          		// 邻接表建图
        List<Integer>[] g = new ArrayList[n];
        Arrays.setAll(g, i -> new ArrayList<>());
        for(int[] e : edges) {
            int x = e[0], y = e[1];
            g[x].add(y);
            g[y].add(x);
        }
        
        // 邻接矩阵建图 
        int[][] g = new int[n][n];
        for(int[] e : edges) {
        	int x = e[0], y = e[1], z = e[2];
        	g[x][y] = z;
        	g[y][x] = z;
        }2. DFS模板
            
            
              java
              
              
            
          
          	// i表示当前节点,n表示节点个数,
	public void dfs(int i, int n, List<List<Integer>> graph, boolean[] visited) {
        visited[i] = true;
        for(int next : graph.get(i)) {
            if (!visited[next] && [Conditions]) {
            	dfs(next, n, graph, visited);
            }
        }
    }3. BFS模板
            
            
              java
              
              
            
          
              public boolean bfs(List<List<Integer>> graph) {
        int n = graph.size();
        boolean[] visited = new boolean[n];
        Queue<Integer> queue = new ArrayDeque<>();
        queue.add(0);
        visited[0] = true;
        while(!queue.isEmpty()) {
            int v = queue.poll();
            for(int w : graph.get(v)) {
                if (!visited[w]) {
                    visited[w] = true;
                    queue.add(w);
                }
            }
        }
    }