建图以及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);
                }
            }
        }
    }
相关推荐
图灵学术计算机论文辅导26 分钟前
论文推荐|迁移学习+多模态特征融合
论文阅读·人工智能·深度学习·计算机网络·算法·计算机视觉·目标跟踪
threejs源码翻译官1 小时前
显微镜图像处理【优化】- 使用图像风格迁移技术放大图像细节
算法
强德亨上校1 小时前
贪心算法(Greedy Algorithm)详解
算法·贪心算法
浮灯Foden2 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
西工程小巴3 小时前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程3 小时前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit3 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
百度Geek说5 小时前
第一!百度智能云领跑视觉大模型赛道
算法
big_eleven5 小时前
轻松掌握数据结构:二叉树
后端·算法·面试
big_eleven5 小时前
轻松掌握数据结构:二叉查找树
后端·算法·面试