《算法》第四章部分程序 part 6
▶ 书中第四章部分程序,加上自己补充的代码,图的环相关
● 无向图中寻找环
package package01; import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.Graph;
import edu.princeton.cs.algs4.Stack; public class class01
{
private boolean[] marked;
private int[] edgeTo;
private Stack<Integer> cycle; // 用来存储环的顶点 public class01(Graph G)
{
if (hasSelfLoop(G))
return;
if (hasParallelEdges(G))
return;
marked = new boolean[G.V()];
edgeTo = new int[G.V()];
for (int v = 0; v < G.V(); v++)
{
if (!marked[v])
dfs(G, -1, v); // 首次调用时参数 u 要赋成非定点编号的值
}
} private void dfs(Graph G, int u, int v) // 深度优先探索,传入起点 v 及其父顶点 u
{
marked[v] = true;
for (int w : G.adj(v))
{
if (cycle != null) // 已经找到环,停止搜索(只搜一个就停)
return;
if (!marked[w])
{
edgeTo[w] = v;
dfs(G, v, w);
}
else if (w != u) // 顶点 w 已经遍历,且边 w-v 不是来边 u-v,说明成环
{
cycle = new Stack<Integer>();
for (int x = v; x != w; x = edgeTo[x]) // 这里 w 指向该环在本次遍历中最早遇到的顶点
cycle.push(x);
cycle.push(w);
cycle.push(v);
}
}
} private boolean hasSelfLoop(Graph G) // 自环
{
for (int v = 0; v < G.V(); v++)
{
for (int w : G.adj(v))
{
if (v == w)
{
cycle = new Stack<Integer>();
cycle.push(v);
cycle.push(v);
return true;
}
}
}
return false;
} private boolean hasParallelEdges(Graph G) // 平行边
{
marked = new boolean[G.V()];
for (int v = 0; v < G.V(); v++)
{
for (int w : G.adj(v))
{
if (marked[w])
{
cycle = new Stack<Integer>();
cycle.push(v);
cycle.push(w);
cycle.push(v);
return true;
}
marked[w] = true;
}
for (int w : G.adj(v)) // 恢复遍历前的状态,一遍其他顶点进行检查
marked[w] = false;
}
return false;
} public boolean hasCycle()
{
return cycle != null;
} public Iterable<Integer> cycle() // 将环用迭代器方式输出
{
return cycle;
} public static void main(String[] args)
{
In in = new In(args[0]);
Graph G = new Graph(in);
class01 finder = new class01(G);
if (finder.hasCycle())
{
for (int v : finder.cycle())
StdOut.print(v + " ");
StdOut.println();
}
else
StdOut.println("\n<main> Graph is aycyclic.\n");
}
}
● 有向图中找环
package package01; import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.Digraph;
import edu.princeton.cs.algs4.Stack; public class class01
{
private boolean[] marked;
private int[] edgeTo;
private boolean[] onStack; // 记录递归顺序,递归回退时需要恢复(marked 不恢复)
private Stack<Integer> cycle; public class01(Digraph G)
{
marked = new boolean[G.V()];
edgeTo = new int[G.V()];
onStack = new boolean[G.V()];
for (int v = 0; v < G.V(); v++)
{
if (!marked[v] && cycle == null)
dfs(G, v);
}
} private void dfs(Digraph G, int v) // 有向图不用传递起点的父顶点
{
onStack[v] = true; // 进入新节点时两个变量都要记录
marked[v] = true;
for (int w : G.adj(v))
{
if (cycle != null)
return;
if (!marked[w])
{
edgeTo[w] = v;
dfs(G, w);
}
else if (onStack[w]) // 用 onStack 来检测本次递归是否已经遍历过顶点 w
{
cycle = new Stack<Integer>();
for (int x = v; x != w; x = edgeTo[x])
cycle.push(x);
cycle.push(w);
cycle.push(v);
}
}
onStack[v] = false; // 递归回退,恢复搜索痕迹
} public boolean hasCycle()
{
return cycle != null;
} public Iterable<Integer> cycle()
{
return cycle;
} public static void main(String[] args)
{
In in = new In(args[0]);
Digraph G = new Digraph(in);
class01 finder = new class01(G);
if (finder.hasCycle())
{
for (int v : finder.cycle())
StdOut.print(v + " ");
StdOut.println();
}
else
StdOut.println("\n<main> Graph is aycyclic.\n");
}
}
● 有向图中找环,广度优先搜索,非递归
package package01; import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.Digraph;
import edu.princeton.cs.algs4.DigraphGenerator;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.Queue; public class class01
{
private Stack<Integer> cycle; public class01(Digraph G)
{
int[] indegree = new int[G.V()];
for (int v = 0; v < G.V(); v++)
indegree[v] = G.indegree(v);
Queue<Integer> queue = new Queue<Integer>();
for (int v = 0; v < G.V(); v++) // 所有入度为 0 的点入队,可作为遍历的起点,且绝对不是环的顶点
{
if (indegree[v] == 0)
queue.enqueue(v);
}
for (; !queue.isEmpty();) // 广度优先遍历,反复将 “入度为 0 的顶点的相邻顶点” 的入度减 1,相当于砍掉所有的链
{
int v = queue.dequeue();
for (int w : G.adj(v))
{
indegree[w]--;
if (indegree[w] == 0)
queue.enqueue(w);
}
}
int[] edgeTo = new int[G.V()]; // 父顶点数组是局部变量就够了
int root = -1; // 初始化为非顶点的编号
for (int v = 0; v < G.V(); v++) // 遍历顶点,如果还有顶点有入度,说明存在环,将其顶点赋给 root
{
if (indegree[v] == 0) // 跳过链中的顶点
continue;
else
root = v;
for (int w : G.adj(v)) // 顺着入度仍大于 0 的顶点往前爬
{
if (indegree[w] > 0)
edgeTo[w] = v;
}
}
if (root != -1) // root 被覆盖,说明存在环,root 值为最后一个换的最后一个顶点
{
cycle = new Stack<Integer>();
//for (boolean[] visited = new boolean[G.V()]; !visited[root]; visited[root] = true, root = edgeTo[root]);
// 源码中维护了最后一个环的顶点集,但是以后再也没有用到,删掉
cycle.push(root);
for (int v = edgeTo[root]; v != root; v = edgeTo[v])
cycle.push(v);
//cycle.push(root); 多压一次根节点
}
} public boolean hasCycle()
{
return cycle != null;
} public Iterable<Integer> cycle()
{
return cycle;
} public static void main(String[] args)
{
int V = Integer.parseInt(args[0]); // 生成 DAG G(V,E),然后再添上 F 条边
int E = Integer.parseInt(args[1]);
int F = Integer.parseInt(args[2]);
Digraph G = DigraphGenerator.dag(V, E);
for (int i = 0; i < F; i++)
{
int v = StdRandom.uniform(V);
int w = StdRandom.uniform(V);
G.addEdge(v, w);
}
StdOut.println(G);
class01 finder = new class01(G);
if (finder.hasCycle())
{
for (int v : finder.cycle())
StdOut.print(v + " ");
StdOut.println();
}
else
StdOut.println("\n<main> Graph is aycyclic.\n");
}
}
《算法》第四章部分程序 part 6的更多相关文章
- 《算法》第四章部分程序 part 19
▶ 书中第四章部分程序,包括在加上自己补充的代码,有边权有向图的邻接矩阵,FloydWarshall 算法可能含负环的有边权有向图任意两点之间的最短路径 ● 有边权有向图的邻接矩阵 package p ...
- 《算法》第四章部分程序 part 18
▶ 书中第四章部分程序,包括在加上自己补充的代码,在有权有向图中寻找环,Bellman - Ford 算法求最短路径,套汇算法 ● 在有权有向图中寻找环 package package01; impo ...
- 《算法》第四章部分程序 part 16
▶ 书中第四章部分程序,包括在加上自己补充的代码,Dijkstra 算法求有向 / 无向图最短路径,以及所有顶点对之间的最短路径 ● Dijkstra 算法求有向图最短路径 package packa ...
- 《算法》第四章部分程序 part 15
▶ 书中第四章部分程序,包括在加上自己补充的代码,Kruskal 算法和 Boruvka 算法求最小生成树 ● Kruskal 算法求最小生成树 package package01; import e ...
- 《算法》第四章部分程序 part 14
▶ 书中第四章部分程序,包括在加上自己补充的代码,两种 Prim 算法求最小生成树 ● 简单 Prim 算法求最小生成树 package package01; import edu.princeton ...
- 《算法》第四章部分程序 part 10
▶ 书中第四章部分程序,包括在加上自己补充的代码,包括无向图连通分量,Kosaraju - Sharir 算法.Tarjan 算法.Gabow 算法计算有向图的强连通分量 ● 无向图连通分量 pack ...
- 《算法》第四章部分程序 part 9
▶ 书中第四章部分程序,包括在加上自己补充的代码,两种拓扑排序的方法 ● 拓扑排序 1 package package01; import edu.princeton.cs.algs4.Digraph ...
- 《算法》第四章部分程序 part 17
▶ 书中第四章部分程序,包括在加上自己补充的代码,无环图最短 / 最长路径通用程序,关键路径方法(critical path method)解决任务调度问题 ● 无环图最短 / 最长路径通用程序 pa ...
- 《算法》第四章部分程序 part 13
▶ 书中第四章部分程序,包括在加上自己补充的代码,图的前序.后序和逆后续遍历,以及传递闭包 ● 图的前序.后序和逆后续遍历 package package01; import edu.princeto ...
- 《算法》第四章部分程序 part 12
▶ 书中第四章部分程序,包括在加上自己补充的代码,图的几种补充数据结构,包括无向 / 有向符号图,有权边结构,有边权有向图 ● 无向符号图 package package01; import edu. ...
随机推荐
- [1] 注解(Annotation)-- 深入理解Java:注解(Annotation)基本概念
转载 http://www.cnblogs.com/peida/archive/2013/04/23/3036035.html 深入理解Java:注解(Annotation)基本概念 什么是注解(An ...
- linux 内存映射-ioremap和mmap函数
最近开始学习Linux驱动程序,将内存映射和ioremap,mmap函数相关资料进行了整理 一,内存映射 对于提供了MMU(存储管理器,辅助操作系统进行内存管理,提供虚实地址转换等硬件支持)的处理器 ...
- sqlserver 全局事务查询
-- 此语句用于查看最老的活动事务.未完成的分布式事务或复制事务的信息. dbcc opentran -- 通过动态管理视图查看活动事务 select*from sys.dm_tran_active_ ...
- 1123.(重、错)Is It a Complete AVL Tree
题意:给定结点个数n和插入序列,判断构造的AVL树是否是完全二叉树? 思路:AVL树的建立很简单.而如何判断是不是完全二叉树呢?通过层序遍历进行判断:当一个结点的孩子结点为空时,则此后就不能有新的结点 ...
- hadoop MapReduce —— 输出每个单词所对应的文件
下面是四个文件及其内容. 代码实现: Mapper: package cn.tedu.invert; import java.io.IOException; import org.apache.had ...
- hierarchical_mutex函数问题(C++ Concurrent in Action)
C++ Concurrent in Action(英文版)书上(No.52-No.53)写的hierarchical_mutex函数,只适合结合std::lock_guard使用,直接使用如果不考虑顺 ...
- vue todolist待办事项完整
<template> <div id="app"> <input type="text" v-model='todo' @keyd ...
- ajax的跨域解决方案(java+ajax)
简单的建立一个后台项目 新建servlet: 内容如下: package a; import java.io.IOException; import java.io.PrintWriter; impo ...
- 第8章 传输层(7)_TCP连接管理
7. TCP连接管理 7.1 TCP的连接建立 (1)三次握手 ①三次握手过程 A.第1.2次握手,数据包的SYN均为1,表示用于同步.即第1次客户端发起请求,并将自己的连接参数(如接收窗口大小.MS ...
- layui之初始化加分页重复请求问题解决
layui框架中的page困扰我很久,一个页面初始化后并且分页,导致初始化渲染请求一次,分页再请求了一次,一个接口就重复请求了2次,通过不停的分析和测试,最终解决了这个问题. 基于JQ的ajax二次封 ...