三种方式的建图和遍历
1,邻接矩阵(适合点的数量不多的图)
2,邻接表(最常用的方式)
3,链式前向星(空间要求严苛情况下使用。比赛必用,大厂笔试、面试不常用)
三种方式建图
// 点的最大数量
public static int MAXN = 11;
// 边的最大数量
// 只有链式前向星方式建图需要这个数量
// 注意如果无向图的最大数量是m条边,数量要准备m*2
// 因为一条无向边要加两条有向边
public static int MAXM = 21;
// 邻接矩阵方式建图
public static int[][] graph1 = new int[MAXN][MAXN];
// 邻接表方式建图
// public static ArrayList<ArrayList<Integer>> graph2 = new ArrayList<>();
public static ArrayList<ArrayList<int[]>> graph2 = new ArrayList<>();
// 链式前向星方式建图
public static int[] head = new int[MAXN];
public static int[] next = new int[MAXM];
public static int[] to = new int[MAXM];
// 如果边有权重,那么需要这个数组
public static int[] weight = new int[MAXM];
public static int cnt;
public static void build(int n) {
// 邻接矩阵清空
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
graph1[i][j] = 0;
}
}
// 邻接表清空和准备
graph2.clear();
// 下标需要支持1~n,所以加入n+1个列表,0下标准备但不用
for (int i = 0; i <= n; i++) {
graph2.add(new ArrayList<>());
}
// 链式前向星清空
cnt = 1;
Arrays.fill(head, 1, n + 1, 0);
}
// 链式前向星加边
public static void addEdge(int u, int v, int w) {
// u -> v , 边权重是w
next[cnt] = head[u];
to[cnt] = v;
weight[cnt] = w;
head[u] = cnt++;
}
// 三种方式建立有向图带权图
public static void directGraph(int[][] edges) {
// 邻接矩阵建图
for (int[] edge : edges) {
graph1[edge[0]][edge[1]] = edge[2];
}
// 邻接表建图
for (int[] edge : edges) {
// graph2.get(edge[0]).add(edge[1]);
graph2.get(edge[0]).add(new int[] { edge[1], edge[2] });
}
// 链式前向星建图
for (int[] edge : edges) {
addEdge(edge[0], edge[1], edge[2]);
}
}
// 三种方式建立无向图带权图
public static void undirectGraph(int[][] edges) {
// 邻接矩阵建图
for (int[] edge : edges) {
graph1[edge[0]][edge[1]] = edge[2];
graph1[edge[1]][edge[0]] = edge[2];
}
// 邻接表建图
for (int[] edge : edges) {
// graph2.get(edge[0]).add(edge[1]);
// graph2.get(edge[1]).add(edge[0]);
graph2.get(edge[0]).add(new int[] { edge[1], edge[2] });
graph2.get(edge[1]).add(new int[] { edge[0], edge[2] });
}
// 链式前向星建图
for (int[] edge : edges) {
addEdge(edge[0], edge[1], edge[2]);
addEdge(edge[1], edge[0], edge[2]);
}
}
三种方式遍历图
public static void traversal(int n) {
System.out.println("邻接矩阵遍历 :");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(graph1[i][j] + " ");
}
System.out.println();
}
System.out.println("邻接表遍历 :");
for (int i = 1; i <= n; i++) {
System.out.print(i + "(邻居、边权) : ");
for (int[] edge : graph2.get(i)) {
System.out.print("(" + edge[0] + "," + edge[1] + ") ");
}
System.out.println();
}
System.out.println("链式前向星 :");
for (int i = 1; i <= n; i++) {
System.out.print(i + "(邻居、边权) : ");
// 注意这个for循环,链式前向星的方式遍历
for (int ei = head[i]; ei > 0; ei = next[ei]) {
System.out.print("(" + to[ei] + "," + weight[ei] + ") ");
}
System.out.println();
}
}
public static void main(String[] args) {
// 理解了带权图的建立过程,也就理解了不带权图
// 点的编号为1...n
// 例子1自己画一下图,有向带权图,然后打印结果
int n1 = 4;
int[][] edges1 = { { 1, 3, 6 }, { 4, 3, 4 }, { 2, 4, 2 }, { 1, 2, 7 }, { 2, 3, 5 }, { 3, 1, 1 } };
build(n1);
directGraph(edges1);
traversal(n1);
System.out.println("==============================");
// 例子2自己画一下图,无向带权图,然后打印结果
int n2 = 5;
int[][] edges2 = { { 3, 5, 4 }, { 4, 1, 1 }, { 3, 4, 2 }, { 5, 2, 4 }, { 2, 3, 7 }, { 1, 5, 5 }, { 4, 2, 6 } };
build(n2);
undirectGraph(edges2);
traversal(n2);
}
拓扑排序
思想
每个节点的前置节点都在这个节点之前
要求:有向图、没有环
拓扑排序的顺序可能不只一种。拓扑排序也可以用来判断有没有环。
1)在图中找到所有入度为0的点
2)把所有入度为0的点在图中删掉,重点是删掉影响!继续找到入度为0的点并删掉影响
3)直到所有点都被删掉,依次删除的顺序就是正确的拓扑排序结果
4)如果无法把所有的点都删掉,说明有向图里有环
拓扑排序模版
例题:课程表 II
现在你总共有 numCourses 门课需要选,记为 0 到 numCourses - 1。给你一个数组 prerequisites ,其中 prerequisites[i] = [ai, bi] ,表示在选修课程 ai 前 必须 先选修 bi 。
例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示:[0,1] 。
返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序,你只要返回 任意一种 就可以了。如果不可能完成所有课程,返回 一个空数组 。
测试链接 : https://leetcode.cn/problems/course-schedule-ii
动态方法(邻接表)
public static int[] findOrder(int numCourses, int[][] prerequisites) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
// 0 ~ n-1
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}
// 入度表
int[] indegree = new int[numCourses];
for (int[] edge : prerequisites) {
graph.get(edge[1]).add(edge[0]);
indegree[edge[0]]++;
}
int[] queue = new int[numCourses];
int l = 0;
int r = 0;
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
queue[r++] = i;
}
}
int cnt = 0;
while (l < r) {
int cur = queue[l++];
cnt++;
for (int next : graph.get(cur)) {
if (--indegree[next] == 0) {
queue[r++] = next;
}
}
}
return cnt == numCourses ? queue : new int[0];
}
静态方法(链式前向星)
题目测试链接:https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c
public class Code02_TopoSortStaticNowcoder {
public static int MAXN = 200001;
public static int MAXM = 200001;
// 建图相关,链式前向星
public static int[] head = new int[MAXN];
public static int[] next = new int[MAXM];
public static int[] to = new int[MAXM];
public static int cnt;
// 拓扑排序,用到队列
public static int[] queue = new int[MAXN];
public static int l, r;
// 拓扑排序,入度表
public static int[] indegree = new int[MAXN];
// 收集拓扑排序的结果
public static int[] ans = new int[MAXN];
public static int n, m;
public static void build(int n) {
cnt = 1;
Arrays.fill(head, 0, n + 1, 0);
Arrays.fill(indegree, 0, n + 1, 0);
}
// 用链式前向星建图
public static void addEdge(int f, int t) {
next[cnt] = head[f];
to[cnt] = t;
head[f] = cnt++;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(br);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) {
n = (int) in.nval;
in.nextToken();
m = (int) in.nval;
build(n);
for (int i = 0, from, to; i < m; i++) {
in.nextToken();
from = (int) in.nval;
in.nextToken();
to = (int) in.nval;
addEdge(from, to);
indegree[to]++;
}
if (!topoSort()) {
out.println(-1);
} else {
for (int i = 0; i < n - 1; i++) {
out.print(ans[i] + " ");
}
out.println(ans[n - 1]);
}
}
out.flush();
out.close();
br.close();
}
public static boolean topoSort() {
l = r = 0;
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
queue[r++] = i;
}
}
int fill = 0;
while (l < r) {
int cur = queue[l++];
ans[fill++] = cur;
// 用链式前向星的方式,遍历cur的相邻节点
for (int ei = head[cur]; ei != 0; ei = next[ei]) {
if (--indegree[to[ei]] == 0) {
queue[r++] = to[ei];
}
}
}
return fill == n;
}
}
题目一:火星字典
问题描述
现有一种使用英语字母的火星语言
这门语言的字母顺序对你来说是未知的。
给你一个来自这种外星语言字典的字符串列表 words
words 中的字符串已经 按这门新语言的字母顺序进行了排序 。
如果这种说法是错误的,并且给出的 words 不能对应任何字母的顺序,则返回 “”
否则,返回一个按新语言规则的 字典递增顺序 排序的独特字符串
如果有多个解决方案,则返回其中任意一个
words中的单词一定都是小写英文字母组成的
测试链接 : https://leetcode.cn/problems/alien-dictionary/
测试链接(不需要会员) : https://leetcode.cn/problems/Jf1JuT/
算法思想
将word里面s的前一个词组和后一个词组字符比较找出谁在谁的前面,这就是一个有权图的边。最后会得到一个有权图,然后进行拓扑排序。能排序结束就是一个顺序,否则就是没顺序。
代码如下
public static String alienOrder(String[] words) {
// 入度表,26种字符
int[] indegree = new int[26];
Arrays.fill(indegree, -1);
for (String w : words) {
for (int i = 0; i < w.length(); i++) {
indegree[w.charAt(i) - 'a'] = 0;
}
}
// 'a' -> 0
// 'b' -> 1
// 'z' -> 25
// x -> x - 'a'
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < 26; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0, j, len; i < words.length - 1; i++) {
String cur = words[i];
String next = words[i + 1];
j = 0;
len = Math.min(cur.length(), next.length());
for (; j < len; j++) {
if (cur.charAt(j) != next.charAt(j)) {
graph.get(cur.charAt(j) - 'a').add(next.charAt(j) - 'a');
indegree[next.charAt(j) - 'a']++;
break;
}
}
if (j < cur.length() && j == next.length()) {
return "";
}
}
int[] queue = new int[26];
int l = 0, r = 0;
int kinds = 0;
for (int i = 0; i < 26; i++) {
if (indegree[i] != -1) {
kinds++;
}
if (indegree[i] == 0) {
queue[r++] = i;
}
}
StringBuilder ans = new StringBuilder();
while (l < r) {
int cur = queue[l++];
ans.append((char) (cur + 'a'));
for (int next : graph.get(cur)) {
if (--indegree[next] == 0) {
queue[r++] = next;
}
}
}
return ans.length() == kinds ? ans.toString() : "";
}
题目二:戳印序列
问题描述
你想最终得到"abcbc",认为初始序列为"???“。印章是"abc”
那么可以先用印章盖出"??abc"的状态,
然后用印章最左字符和序列的0位置对齐,就盖出了"abcbc"
这个过程中,"??abc"中的a字符,被印章中的c字符覆盖了
每次盖章的时候,印章必须完全盖在序列内
给定一个字符串target是最终的目标,长度为n,认为初始序列为n个’?’
给定一个印章字符串stamp,目标是最终盖出target,但是印章的使用次数必须在10n次以内
返回一个数组,该数组由每个回合中被印下的最左边字母的索引组成
上面的例子返回[2,0],表示印章最左字符依次和序列2位置、序列0位置对齐盖下去,就得到了target
如果不能在10n次内印出序列,就返回一个空数组
测试链接 : https://leetcode.cn/problems/stamping-the-sequence
算法思想
算每个位置假设它开始盖印章能错几个位置。如果都没错,那他肯定是最后一个盖的,然后看它能修正哪几个位置,消除影响来得到下一个没有错的位置(入度为0)。最后得到拓扑排序序列
代码如下
public class Code05_StampingTheSequence {
public static int[] movesToStamp(String stamp, String target) {
char[] s = stamp.toCharArray();
char[] t = target.toCharArray();
int m = s.length;
int n = t.length;
int[] indegree = new int[n - m + 1];
Arrays.fill(indegree, m);
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
int[] queue = new int[n - m + 1];
int l = 0, r = 0;
// O(n*m)
for (int i = 0; i <= n - m; i++) {
// i开头....(m个)
// i+0 i+1 i+m-1
for (int j = 0; j < m; j++) {
if (t[i + j] == s[j]) {
if (--indegree[i] == 0) {
queue[r++] = i;
}
} else {
// i + j
// from : 错误的位置
// to : i开头的下标
graph.get(i + j).add(i);
}
}
}
// 同一个位置取消错误不要重复统计
boolean[] visited = new boolean[n];
int[] path = new int[n - m + 1];
int size = 0;
while (l < r) {
int cur = queue[l++];
path[size++] = cur;
for (int i = 0; i < m; i++) {
// cur : 开头位置
// cur + 0 cur + 1 cur + 2 ... cur + m - 1
if (!visited[cur + i]) {
visited[cur + i] = true;
for (int next : graph.get(cur + i)) {
if (--indegree[next] == 0) {
queue[r++] = next;
}
}
}
}
}
if (size != n - m + 1) {
return new int[0];
}
// path逆序调整
for (int i = 0, j = size - 1; i < j; i++, j--) {
int tmp = path[i];
path[i] = path[j];
path[j] = tmp;
}
return path;
}
}
题目三:字典序最小的拓扑排序
问题描述
字典序最小的拓扑排序
要求返回所有正确的拓扑排序中 字典序最小 的结果
建图请使用链式前向星方式,因为比赛平台用其他建图方式会卡空间
测试链接 : https://www.luogu.com.cn/problem/U107394
算法思想
使用拓扑排序加小根堆
代码如下
public class Code03_TopoSortStaticLuogu {
public static int MAXN = 100001;
public static int MAXM = 100001;
// 建图相关,链式前向星
public static int[] head = new int[MAXN];
public static int[] next = new int[MAXM];
public static int[] to = new int[MAXM];
public static int cnt;
// 拓扑排序,不用队列,用小根堆,为了得到字典序最小的拓扑排序
public static int[] heap = new int[MAXN];
public static int heapSize;
// 拓扑排序,入度表
public static int[] indegree = new int[MAXN];
// 收集拓扑排序的结果
public static int[] ans = new int[MAXN];
public static int n, m;
// 清理之前的脏数据
public static void build(int n) {
cnt = 1;
heapSize = 0;
Arrays.fill(head, 0, n + 1, 0);
Arrays.fill(indegree, 0, n + 1, 0);
}
// 用链式前向星建图
public static void addEdge(int f, int t) {
next[cnt] = head[f];
to[cnt] = t;
head[f] = cnt++;
}
// 小根堆里加入数字
public static void push(int num) {
int i = heapSize++;
heap[i] = num;
// heapInsert的过程
while (heap[i] < heap[(i - 1) / 2]) {
swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
// 小根堆里弹出最小值
public static int pop() {
int ans = heap[0];
heap[0] = heap[--heapSize];
// heapify的过程
int i = 0;
int l = 1;
while (l < heapSize) {
int best = l + 1 < heapSize && heap[l + 1] < heap[l] ? l + 1 : l;
best = heap[best] < heap[i] ? best : i;
if (best == i) {
break;
}
swap(best, i);
i = best;
l = i * 2 + 1;
}
return ans;
}
// 判断小根堆是否为空
public static boolean isEmpty() {
return heapSize == 0;
}
// 交换堆上两个位置的数字
public static void swap(int i, int j) {
int tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(br);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) {
n = (int) in.nval;
in.nextToken();
m = (int) in.nval;
build(n);
for (int i = 0, from, to; i < m; i++) {
in.nextToken();
from = (int) in.nval;
in.nextToken();
to = (int) in.nval;
addEdge(from, to);
indegree[to]++;
}
topoSort();
for (int i = 0; i < n - 1; i++) {
out.print(ans[i] + " ");
}
out.println(ans[n - 1]);
}
out.flush();
out.close();
br.close();
}
public static void topoSort() {
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
push(i);
}
}
int fill = 0;
while (!isEmpty()) {
int cur = pop();
ans[fill++] = cur;
// 用链式前向星的方式,遍历cur的相邻节点
for (int ei = head[cur]; ei != 0; ei = next[ei]) {
if (--indegree[to[ei]] == 0) {
push(to[ei]);
}
}
}
}
}