Skip to content

Commit

Permalink
add Digraph in unit7
Browse files Browse the repository at this point in the history
  • Loading branch information
zzzzzzch committed Apr 19, 2018
1 parent 4ddaede commit b28b22d
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 0 deletions.
54 changes: 54 additions & 0 deletions unit-7/BreadthFirstDirectedPaths.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
public class BreadthFirstDirectedPaths {
private Queue<Integer> queue;
private boolean[] marked;
private int[] distTo;
private int[] edgeTo;

public BreadthFirstDirectedPaths(Digraph G, int s) {
queue = new Queue<Integer>();
marked = new boolean[G.V()];
distTo = new int[G.V()];
edgeTo = new int[G.V()];
bfs(G, s);
}

private void bfs(Digraph G, int v) {
marked[v] = true;
distTo[v] = 0;
queue.enqueue(v);
while (!queue.isEmpty()) {
int w = queue.dequeue();
for (int i : G.adj(w)) {
if(!marked[i]) {
marked[i] = true;
distTo[i] = distTo[w] + 1;
edgeTo[i] = w;
queue.enqueue(i);
}
}
}
}

public boolean hasPathTo(int v) {
return marked[v];
}

public int distTo(int v) {
return distTo[v];
}

public Iterable<Integer> pathTo(int v) {
if (!hasPathTo(v)) {
return null;
}
Stack<Integer> path = new Stack<Integer>();

for (int i = v; i != s; i = edgeTo[i]) {
path.push(i);
}

path.push(s);

return path;
}
}
17 changes: 17 additions & 0 deletions unit-7/DepthFirstSearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class DepthFirstSearch {
private Boolean[] marked;

public DepthFirstSearch(Digraph G, int s) {
marked = new Boolean[G.V()];
dfs(G, s);
}

private void dfs(Digraph G, int v) {
marked[v] = true;
for (int w : adj[v]) {
if (!marked[w]) {
dfs(G, w);
}
}
}
}
42 changes: 42 additions & 0 deletions unit-7/Digraph.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
public class Digraph {
private int V;
private int E;
private Bag<Integer>[] adj;

public Digraph (int V) {
this.V = V;
this.E = 0;
adj = (Bag<Integer>[]) new Bag[V]; //数组不支持泛型,需要强制转换
for (int i =0; i < V; i++) {
adj[i] = new Bag<Integer>();
}
}

public void addEdge(int v, int w) {
adj[v].add(w);
E++;
}

public int V() {
return V;
}

public int E() {
return E;
}

public Iterable<Integer> adj(int v) {
return adj[v];
}

public Digraph reverse() {
Digraph R = new Digraph(V);
for (int i = 0; i < V; v++) {
for (int w : adj(v)) {
R.addEdge(w, v);
}
}

return R;
}
}
21 changes: 21 additions & 0 deletions unit-7/DirectedDFS.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
public class DirectedDFS {
private Boolean[] marked;

public DirectedDFS(Digraph G, int s) {
marked = new Boolean[G.V()];
dfs(G, s);
}

private void dfs(Digraph G, int v) {
marked[v] = true;
for (int w : adj[v]) {
if (!marked[w]) {
dfs(G, w);
}
}
}

public Boolean visited(int v) {
return marked[v];
}
}

0 comments on commit b28b22d

Please sign in to comment.