建图以及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);
                }
            }
        }
    }
相关推荐
Frostnova丶1 分钟前
【算法笔记】数学知识
笔记·算法
吴可可12326 分钟前
AutoCAD 2016与2014二次开发关键差异
算法
雨白1 小时前
哈希:以时间换空间的算法实战
算法
San813_LDD3 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x138702859573 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油5 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero5 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称5 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划