Thursday, February 22nd, 2024

ECS122A Lecture: Intro to Graph

  • graph
    • directed vs undirected
    • dense graph: (an edge is an ordered pair of vertices) so
      • example: disease/infection, genome analysis
      • adjacency matrix
        • time: to check edge
        • space:
    • sparse graph:
      • example: social interaction
      • adjacency list
        • time to look up edge: (a vertex can be connected to all other vertices in the worst case, and we need to check one by one, unless it’s a sorted list, then it’s )
        • time to list all edges:
        • space: (e.g. a hash map entry for each vertex, and the entire map contains edges)
  • breadth-first search distance algorithm analysis
    • input: unweighted graph, start vertex s
    • output: dist, where dist[v] is the distance between s and v
    • code
      • initialize dist[:] to infinity
      • d[s] = 0
      • create a queue that initially contains start node
      • while queue is not empty
        • pop node u from queue
        • for each node v adjacent to u
          • if v has not been visited (d[v] == inf)
            • d[v] = d[u] + 1
            • push v into the queue
    • example
      • input
        • Graph G as a
          • S: A, C, G
          • A: S, B
          • B: A
          • C: S, D, E, F
          • D: C
          • E: C, H
          • F: C, G
          • G: S, F, H
          • H: E, G
    • runtime:
      • if graph is stored as adjacency list: , ( for max vertices in queue, since each edge is processed exactly once)
      • if graph is stored as adjacency matrix: ( for max vertices in queue, then to get the adjacent nodes for each node)

BFS runtime comparison:

StorageSpaceDense Graph RuntimeSparse Graph Runtime
adjacency list ()
adjacency matrix
  • depth-first search
    • allows detecting cycle in time
    • create a tree out of an (directed) acyclic graph (by removing edges when necessary to prevent a node from having more than one parents)
    • code
      • color[v] = White
      • for each node u in graph
        • if color[u] == White
          • color[u] = Gray
          • start_time[u] = time
          • for each adjacent node v in graph:
            • dfs(v)
          • color[v] = Black
          • finish_time[u] = time
    • function of setting colors
      • if there’s an edge white gray, then it’s a tree node
      • if there’s an edge gray gray, then it’s a “backward node”, which means there’s a cycle
      • if there’s an edge gray black, then it’s a forward edge (an edge from ancestor to dependent)