Graph

Graph types

  • Undirected

  • Directed

    • Cycle detection

  • Weighted

    • Shortest path -> Dijkstras algorithm

Implementation

  • Adjacent list List<List<Integer>> adjList = new ArrayList<List<Integer>>(n);

  • Usually, the implementation fuse into Solution, no need to new a Graph Class.

  • detect loop

class Graph {
    private final int V;
    private int E;
    List<List<Integer>> adjList;
    public Graph(int v) {
        this.V = v; this.E = 0;
        adjList = new ArrayList<List<Integer>>();
        for (int i = 0; i < n; i++) {
            adjList.add(new ArrayList<Integer>());
        }
    }
    public void addEdge(int v, int w) {
        adjList.get(v).add(w);
        adjList.get(w).add(v);
        E++;
    }
    public List<Integer> adj(int v) {
        return adjList.get(v);
    }
}

Topological sorting

DFS

https://leetcode.com/problems/number-of-islands/description/

BFS

https://leetcode.com/problems/number-of-islands/description/

Cycle detection

1) graph, DFS/BFS 2) topological sort 3) Floyd cycle 4) Union Find

Shortest Path problem

Simple BFS

Not weighted graph

Dijkstra's Algorithm

Bellman–Ford Algorithm

Shortest Path Faster Algorithm (SPFA) - improvement of the Bellman-Ford

  • O(EV) worst case, in practice it's faster though.

  • Different from Bellman-Ford: only track those nodes with updated distance, whereas BF track every node.

  • Can handle negative weight: one node cann't be enqueued more than V times;

Floyd–Warshall algorithm

Last updated

Was this helpful?