Skip to content

Commit

Permalink
add graph
Browse files Browse the repository at this point in the history
  • Loading branch information
knewbie committed Apr 19, 2017
1 parent 172011b commit ecfecdd
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 1 deletion.
89 changes: 89 additions & 0 deletions Graph.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { print } from "./util";

export class Graph<T> {
private vertices: number;
private edges: number;
private adj: any;
private dfs_marked: any;
private bfs_marked: any;
private path: any;
constructor(n: number) {
this.vertices = n;
this.edges = 0;
this.adj = {};
this.dfs_marked = {};
this.bfs_marked = {};
this.path = {};
}

public addEdge(v: T, w: T) {
if (this.adj[v] == undefined) {
this.adj[v] = new Array<T>();
}
if (this.adj[w] == undefined) {
this.adj[w] = new Array<T>();
}
this.adj[v].push(w);
this.adj[w].push(v);
this.edges++;
}

// depth first search
public dfs(v: T) {
this.dfs_marked[v] = true;
if (this.adj[v] != undefined) {
print("[DFS] Visited vertex: ", v);
}
let d = this.adj[v];
for (let w of d) {
if (!this.dfs_marked[w]) {
this.dfs(w);
}
}
}
// broad first search
public bfs(v: T) {
let queue = new Array<T>();
if (this.adj[v] != undefined) {
queue.push(v);
}
do {
let w = queue.shift();
print("[BFS] Visited vertex: ", w);
this.bfs_marked[w] = true;
let d = this.adj[w];
for (let v of d) {
if (!this.bfs_marked[v]) {
this.path[v] = w;
queue.push(v);
}
}
} while (queue.length > 0);
}


// find the shortest path
public findShortestPath(v: T):T[] {
let path = [];
if(!this.bfs_marked[v]) {
print("no edge to vertex or no vertex in the graph: ",v);
return undefined;
}
for(let e = v; e!=undefined; e=this.path[e]){
path.push(e);
}
return path;
}


public showGraph() {
for (let k in this.adj) {
let s = k + " -> ";
let d = this.adj[k];
for (let j = 0; j < d.length; j++) {
s += d[j] + ' ';
}
print(s);
}
}
}
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
- [X] 集合(Set)
- [X] 二叉树(BiTree)
- [X] 二叉查找树(BST)
- [ ] 图(Grap)
- [X] 图(Grap)
- [ ] 排序算法(Sort)
- [ ] 查找算法(Search)


(未完待续....)
Expand Down
32 changes: 32 additions & 0 deletions test_Graph.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

import { Graph } from "./Graph";
import { print } from "./util";



let g = new Graph<number>(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
// g.addEdge(3,4);
g.showGraph();

// g.dfs(0);

g.bfs(0);
// g.dfs(1);

print("------")
let p = g.findShortestPath(3);
if (p.length > 0) {
let s = '';
while (p.length > 0) {
if (p.length > 1) {
s += p.pop() + " -> ";
} else {
s += p.pop();
}
}
print("PATH: ",s);
}

0 comments on commit ecfecdd

Please sign in to comment.