建图以及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);
                }
            }
        }
    }
相关推荐
Fanxt_Ja2 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶2 小时前
算法 --- 字符串
算法
博笙困了2 小时前
AcWing学习——差分
c++·算法
NAGNIP2 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP2 小时前
大模型微调框架之LLaMA Factory
算法
echoarts2 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客2 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法
徐小夕3 小时前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
小刘鸭地下城3 小时前
深入浅出链表:从基础概念到核心操作全面解析
算法