当前位置: 首页 > news >正文

算法模板(Java版)_DFS与BFS

@ZZHow(ZZHow1024)

搜索方式数据结构空间特点
DFSSteakO(h)O(h)O(h)不具有最短路
BFSQueueO(2h)O(2 ^ h)O(2h)最短路

DFS

DFS(深度优先搜索),回溯时记得回复现场。

必要时进行剪枝操作。

  • 例题:AcWing 842. 排列数字
import java.util.Scanner;public class Main {static int n;static int[] path;static boolean[] st;public static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt();path = new int[n + 1];st = new boolean[n + 1];dfs(0);}public static void dfs(int u) {if (u == n) {for (int i = 0;i < n; i++)System.out.print(path[i] + " ");System.out.println();return;}for (int i = 1; i <= n; i++) {if (!st[i]) {st[i] = true;path[u] = i;dfs(u + 1);st[i] = false;}}}
}
  • 例题:AcWing 843. n-皇后问题
  1. 按行搜索
import java.util.Scanner;public class Main {static final int N = 20;static int n;static char[][] g = new char[N][N];static boolean[] col = new boolean[N];static boolean[] dg = new boolean[N];static boolean[] udg = new boolean[N];public static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt();for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)g[i][j] = '.';dfs(0);}public static void dfs(int u) {// 搜索出一组答案if (u == n) {for (int i = 0; i < n; i++){for (int j = 0; j < n; j++)System.out.print(g[i][j]);System.out.println();}System.out.println();}// 枚举一行可以放棋子的位置for (int i = 0; i < n; i++) {if (!col[i] && !dg[u + i] && !udg[n - u + i]) {g[u][i] = 'Q';col[i] = dg[u + i] = udg[n - u + i] = true;dfs(u + 1);col[i] = dg[u + i] = udg[n - u + i] = false;g[u][i] = '.';}}}
}
  1. 按格子依次搜索
import java.util.Scanner;public class Main {static final int N = 20;static int n;static char[][] g = new char[N][N];static boolean[] row = new boolean[N];static boolean[] col = new boolean[N];static boolean[] dg = new boolean[N];static boolean[] udg = new boolean[N];public static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt();for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)g[i][j] = '.';dfs(0, 0, 0);}public static void dfs(int x, int y, int s) {// 行出界if (y == n) {y = 0;x++;}// 搜索出一组答案if (x == n) {if (s == n) {for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++)System.out.print(g[i][j]);System.out.println();}System.out.println();}return;}// 不放皇后dfs(x, y + 1, s);// 放皇后if (!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n]) {g[x][y] = 'Q';row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;dfs(x, y + 1, s + 1);row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;g[x][y] = '.';}}
}

BFS

BFS(宽度优先搜索),使用队列。

  • 例题:AcWing 844. 走迷宫
import java.util.Scanner;public class Main {static final int N = 110;static int n;static int m;static int[][] g = new int[N][N];static int[][] d = new int[N][N];static Pair[] q = new Pair[N * N];public static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt();m = scanner.nextInt();for (int i = 0; i < n; i++)for (int j = 0; j < m; j++)g[i][j] = scanner.nextInt();System.out.println(bfs());}public static int bfs() {// 队头int hh = 0;// 队尾int tt = 0;q[0] = new Pair(0, 0);for (int i = 0; i < d.length; i++)for (int j = 0; j < d[i].length; j++)d[i][j] = -1;d[0][0] = 0;int[] dx = {-1, 0, 1, 0};int[] dy = {0, 1, 0, -1};while (hh <= tt) {Pair t = q[hh++]; // 取出队头for (int i = 0; i < 4; i++) {int x = t.first + dx[i];int y = t.second + dy[i];if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {d[x][y] = d[t.first][t.second] + 1;q[++tt] = new Pair(x, y);}}}return d[n - 1][m - 1];}
}class Pair {public int first;public int second;public Pair(int first, int second) {this.first = first;this.second = second;}
}

树与图的深度优先遍历

树是一种特殊的图(无环连通图)

有向图的存储方法

  1. 邻接矩阵
  2. 邻接表
  • 例题:AcWing 846. 树的重心
import java.util.Scanner;public class Main {static final int N = 100010;static final int M = N * 2;static int n;static int[] h = new int[N];static int[] e = new int[M];static int[] ne = new int[M];static boolean[] st = new boolean[N];static int idx = 0;static int ans = N;public static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt();for (int i = 0; i < h.length; i++)h[i] = -1;for (int i = 0; i < n - 1; i++) {int a = scanner.nextInt();int b = scanner.nextInt();add(a, b);add(b, a);}bfs(1);System.out.println(ans);}public static void add(int a, int b) {e[idx] = b;ne[idx] = h[a];h[a] = idx++;}public static int bfs(int u) {st[u] = true;int sum = 1; // 当前子树的大小int res = 0; // 删除当前点后连通块的最大值for (int i = h[u]; i != -1; i = ne[i]) {int j = e[i];if (!st[j]) {int s = bfs(j);res = Math.max(res, s);sum += s;}}res = Math.max(res, n - sum);ans = Math.min(ans, res);// 返回当前子树的大小return sum;}
}

树与图的广度优先遍历

重边:两个点之间有两条边

自环:一条边指向自己

  • 例题:AcWing 847. 图中点的层次
import java.util.Scanner;public class Main {static final int N = 100010;static int n;static int m;static int[] h = new int[N];static int[] e = new int[N];static int[] ne = new int[N];static int idx = 0;static int[] q = new int[N];static int[] d = new int[N];public static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt();m = scanner.nextInt();for (int i = 0; i <= n; i++)h[i] = -1;while (m-- != 0) {int a = scanner.nextInt();int b = scanner.nextInt();add(a, b);}System.out.println(bfs());}public static void add(int a, int b) {e[idx] = b;ne[idx] = h[a];h[a] = idx++;}public static int bfs() {int hh = 0;int tt = 0;for (int i = 0; i <= n; i++)d[i] = -1;q[0] = 1;d[1] = 0;while (hh <= tt) {int t = q[hh++];for (int i = h[t]; i != -1; i = ne[i]) {int j = e[i];if (d[j] == -1) {d[j] = d[t] + 1;q[++tt] = j;}}}return d[n];}
}

有向图的拓扑序列

  • 例题:AcWing 848. 有向图的拓扑序列
import java.util.Scanner;public class Main {static final int N = 100010;static int n;static int m;static int[] h = new int[N];static int[] e = new int[N];static int[] ne = new int[N];static int idx = 0;static int[] q = new int[N];static int[] d = new int [N];public static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt();m = scanner.nextInt();for (int i = 0; i <= n; i++)h[i] = -1;while (m-- != 0) {int a = scanner.nextInt();int b = scanner.nextInt();add(a, b);d[b]++;}if (topSort()) {for (int i = 0; i < n; i++)System.out.print(q[i] + " ");} else {System.out.println("-1");}}public static void add(int a, int b) {e[idx] = b;ne[idx] = h[a];h[a] = idx++;}public static boolean topSort() {int hh = 0;int tt = -1;for (int i = 1; i <= n; i++)if (d[i] == 0)q[++tt] = i;while (hh <= tt) {int t = q[hh++];for (int i = h[t]; i != -1; i = ne[i]) {int j = e[i];d[j]--;if (d[j] == 0)q[++tt] = j;}}return tt == n - 1;}
}

文章转载自:

http://4VCkqp6L.xgLgm.cn
http://w64zhFXJ.xgLgm.cn
http://vJHirstd.xgLgm.cn
http://N7xbMXey.xgLgm.cn
http://PlMgdMXD.xgLgm.cn
http://JEFmvQ7X.xgLgm.cn
http://HdUM7zPA.xgLgm.cn
http://gfBxi9E8.xgLgm.cn
http://zirTcJAT.xgLgm.cn
http://RZSvgyQI.xgLgm.cn
http://7l5c7rsW.xgLgm.cn
http://b03NOBGA.xgLgm.cn
http://qACaQ5Dj.xgLgm.cn
http://YFqHKKw5.xgLgm.cn
http://WPx5AgMg.xgLgm.cn
http://YjrfKNig.xgLgm.cn
http://Kmck9QU1.xgLgm.cn
http://to9M4PcJ.xgLgm.cn
http://gcIJzkgI.xgLgm.cn
http://7tmGqkJ4.xgLgm.cn
http://YMULV9XJ.xgLgm.cn
http://X850Oob5.xgLgm.cn
http://iilqXrY7.xgLgm.cn
http://C6Vjfazu.xgLgm.cn
http://RJgE0jlp.xgLgm.cn
http://6RdtcASH.xgLgm.cn
http://9rhdhM1c.xgLgm.cn
http://GpLsYt0R.xgLgm.cn
http://A9v7Eypt.xgLgm.cn
http://vy1IDPGQ.xgLgm.cn
http://www.dtcms.com/a/368754.html

相关文章:

  • 一分钟了解Modbus 转 IEC61850 网关
  • Webpack 有哪些特性?构建速度?如何优化?
  • 2025精选5款AI视频转文字工具,高效转录秒变文字!
  • 【最新版】发烧级完美解码播放器PureCodec v2025.08.29 中文免费版_电脑播放器影音解码包
  • 阿里云国际代理:阿里云的云数据库是什么?
  • 盲盒抽卡机小程序功能版块设计的合理性评估维度
  • Memory write error at 0x100000. MMU page translation fault
  • 纯血鸿蒙开发入门:2.展示hello world
  • 【1】策略模式 + 模板方法模式的联合应用
  • 突发奇想,还未实践,在Vben5的Antd模式下,将表单从「JS 配置化」改写成「模板可视化」形式(豆包版)
  • Flash Attention:突破大模型推理内存瓶颈的革命性算法
  • 【正则表达式】 正则表达式的分组和引用
  • 具身智能的工程落地:视频-控制闭环的实践路径
  • E+H音叉开关FTL31-AA4M2AAWBJ
  • Android 权限机制默认授权分析
  • 深入理解 HarmonyOS Stage 模型与 UIAbility 生命周期管理
  • Vue3中的数据响应【4】
  • 因泰立科技:用激光雷达重塑智能工厂物流生态
  • 【Windows】通过 runas 命令实现多用户权限测试的完整流程
  • LangChain实战(十六):构建基于SQL数据库的数据分析Agent
  • Struts2 工作总结
  • 软件设计模式之单例模式
  • 小迪安全v2023学习笔记(七十八讲)—— 数据库安全RedisCouchDBH2database未授权CVE
  • 【Go】P2 Golang 常量与变量
  • Leetcode—721. 账户合并【中等】
  • Go初级之十:错误处理与程序健壮性
  • Go语言的编译和运行过程
  • Golang语言设计理念
  • Golang Goroutine 与 Channel:构建高效并发程序的基石
  • Golang中的context包介绍及源码阅读