Data Structures and Algorithms

muigai unaka

Week 7

Graph

A

B

C

D

E

F

A collection of nodes (or vertices) connected to each other by edges. A graph G is an ordered pair of a set V of vertices and a set E of edges

Graph Examples

Social network, where a user is a node & friendship is an edge

Flights for cities, where a city/airport is a node & flight path is an edge

The world wide web, where a url is a node & a link to a page is an edge

When to use a Graph

Representing links. Graphs are ideal for cases where you're working with things that connect to other things. Nodes and edges could, for example, respectively represent cities and highways, routers and ethernet cables, or Facebook users and their friendships.

Cons to using a Graph

Scaling challenges. Most graph algorithms are O(n∗lg(n))O(n*lg(n))O(nlog(n)) or even slower. Depending on the size of your graph, running algorithms across your nodes may not be feasible.

A

B

C

D

Directed Graph

A

B

C

D

Undirected Graph

Graph Terms

Node (or vertex) contains pointers to other nodes

Directed graph when the relationship from node to node is one way

Undirected graph is when the relationship is both ways

Edge is a one to one connection between nodes

Path is the sequence of nodes along the edges of a graph

Visiting is accessing a node in a graph

Traversal is the act of passing through nodes in a specific way

Self-loop is when an edge starts where it ends

 

 

3 main ways to represent a Graph

  • adjacency list

  • adjacency matrix

  • incidence matrix

Graph implemented with adjacency list

function Graph() {
  	// Graph represented using an Adjacency List
	this.graph_representation = new Map();
	this.add_node = (node) => {
		this.graph_representation[node] = []
    }
    this.add_vertex = (node_from, node_to) => {
      	this.graph_representation[node_from].push(node_to);
    }
    this.bfs = (start_node) => {
      // implemented later
    }
    this.dfs = (start_node) => {
      // implemented later
    }
}

Breadth First Search

Breadth-first search involves each child of a node being visited before any of that child's children are visited

BFS (adjacency list)

function Graph() {
    // Graph represented using an Adjacency List
    this.graph_representation = new Map();
    // level by level search of the graph
    // goes broad to neighbors before going to children
    this.bfs(start_node) {
        // create visited boolean map
        let visited = new Map()
        // initiate queue
        let q = [];
        // mark starting node as visited
        visited.set(start_node, true)
        q.push(start_node);
        // iterate through each value
        while (q.length) {
            let current = q.shift()
            console.log(current);
            let current_neighbors = this.graph_representation.get(current);

            for (let vertex of current_neighbors) {
                if (!visited.has(vertex)) {
                    visited.set(vertex, true)
                    q.push(vertex)
                }
            }
        }
    }
}

Depth First Search

Depth-first search involves following a sequence of vertices connected by edges until we cannot any more. We then continue to the original start node's next child

DFS (adjacency list)

function Graph() {
    // Graph represented using an Adjacency List
    this.graph_representation = new Map();
    /**
     * The only catch here is, unlike trees, graphs may contain cycles, 
     * so we may come to the same node again. To avoid processing a node 
     * more than once, we use a boolean visited array/Set.
     */
    this.dfs(start_node) {
        let visited = new Set()
        let stack = []
        stack.push(start_node)

        while (stack.length) {
            let current_vertex = stack.pop()
            visited.add(current_vertex)
            console.log(current_vertex)

            let current_neighbors = this.graph_representation.get(current_vertex)
            
            for (let vertex of current_neighbors) {
                if (!visited.has(vertex)) {
                    stack.push(vertex)
                }
            }
        }
    }
}

Spurningum?

Made with Slides.com