GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — JavaScript/Data-Structures/Graph/Graph3.js at master · TheAlgorithms/JavaScript Expand file tree/ Copy pathGraph3.jsMore file actions 108 lines (89 loc) · 2.24 KB / Copy pathGraph3.jsFile metadata and controls108 lines (89 loc) · 2.24 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 class Graph { constructor() { this.adjacencyObject = {} } addVertex(vertex) { if (!this.adjacencyObject[vertex]) this.adjacencyObject[vertex] = [] } addEdge(vertex1, vertex2) { this.adjacencyObject[vertex1].push(vertex2) this.adjacencyObject[vertex2].push(vertex1) } removeEdge(vertex1, vertex2) { this.adjacencyObject[vertex1] = this.adjacencyObject[vertex1].filter( (v) => v !== vertex2 ) this.adjacencyObject[vertex2] = this.adjacencyObject[vertex2].filter( (v) => v !== vertex1 ) } removeVertex(vertex) { while (this.adjacencyObject[vertex].length) { const adjacentVertex = this.adjacencyObject[vertex].pop() this.removeEdge(vertex, adjacentVertex) } } /** * Return DFS (Depth First Search) List Using Recursive Method */ DFS(start) { if (!start) return null const result = [] const visited = {} const adjacencyObject = this.adjacencyObject function dfs(vertex) { if (!vertex) return null visited[vertex] = true result.push(vertex) adjacencyObject[vertex].forEach((neighbor) => { if (!visited[neighbor]) { dfs(neighbor) } }) } dfs(start) return result } /** * Return DFS(Depth First Search) List Using Iteration */ DFSIterative(start) { if (!start) return null const stack = [start] const visited = {} visited[start] = true const result = [] let currentVertex while (stack.length) { currentVertex = stack.pop() result.push(currentVertex) this.adjacencyObject[currentVertex].forEach((neighbor) => { if (!visited[neighbor]) { visited[neighbor] = true stack.push(neighbor) } }) } return result } BFS(start) { if (!start) return null const queue = [start] const visited = {} visited[start] = true let currentVertex const result = [] while (queue.length) { currentVertex = queue.shift() result.push(currentVertex) this.adjacencyObject[currentVertex].forEach((neighbor) => { if (!visited[neighbor]) { visited[neighbor] = true queue.push(neighbor) } }) } return result } } export { Graph } |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |