(1) 深度优先遍历 —— 模板题 AcWing 846. 树的重心(层序遍历,用到了回溯+剪枝,深搜没有一个常用的框架)
int dfs(int u)
{
st[u] = true; // st[u] 表示点u已经被遍历过
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j]) dfs(j);
}
}
(2) 宽度优先遍历 —— 模板题 AcWing 847. 图中点的层次(最短路,宽搜有一个最常用的框架)
queue<int> q;
st[1] = true; // 表示1号点已经被遍历过
q.push(1);
while (q.size())
{
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (!s[j])
{
st[j] = true; // 表示点j已经被遍历过
q.push(j);
}
}
}
例子:
对123排列组合:
package com.huawei.it.acwing;
import java.io.IOException;
public class Main {
private static final int n = 3;
private static final int[] path = new int[10];
private static final boolean[] st = new boolean[10];
public static void

最低0.47元/天 解锁文章
1229

被折叠的 条评论
为什么被折叠?



