建图以及DFS、BFS模板

(/≧▽≦)/~┴┴ 嗨~我叫小奥 ✨✨✨

👀👀👀 个人博客:小奥的博客

👍👍👍:个人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);
                }
            }
        }
    }
相关推荐
方案开发PCBA抄板芯片解密31 分钟前
什么是算法:高效解决问题的逻辑框架
算法
songx_9942 分钟前
leetcode9(跳跃游戏)
数据结构·算法·游戏
小白狮ww1 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥1 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
kk”2 小时前
C语言快速排序
数据结构·算法·排序算法
纪元A梦2 小时前
贪心算法应用:基因编辑靶点选择问题详解
算法·贪心算法
3壹2 小时前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
skytier3 小时前
Construct内报错和定位解决
算法
skytier3 小时前
Ascend print数据落盘使用
算法
etcix3 小时前
dmenux.c: integrate dmenu project as one file
c语言·前端·算法