> For the complete documentation index, see [llms.txt](https://zike.gitbook.io/princeton-algorithms-notebook-python/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zike.gitbook.io/princeton-algorithms-notebook-python/ii.1.1-undirected-graphs.md).

# II.1.1 Undirected Graphs

Algorithm II Week 1: Undirected Graphs

## Graph&#x20;

**Graph**. Set of vertices connected pairwise by edges.

### Some Problems

* **Path**. Is there a path between s and t ?
  * **Shortest path**. What is the shortest path between s and t ?
* **Cycle**. Is there a cycle in the graph?
  * **Euler tour**. Is there a cycle that uses each edge exactly once?
  * **Hamilton tour**. Is there a cycle that uses each vertex exactly once.
* **Connectivity**. Is there a way to connect all of the vertices?
  * **MST**. What is the best way to connect all of the vertices?
  * **Biconnectivity**. Is there a vertex whose removal disconnects the graph?
* **Planarity**. Can you draw the graph in the plane with no crossing edges?
* **Graph isomorphism**. Do two adjacency lists represent the same graph?

### Graph API

```
Class Graph:
    void add_edge(int v, int w)
    list adj(inv)
    int num_of_V()
    int num_of_E()
    str to_string()
```

Representation

1. Set-of-edges representation (linked list or array)<img src="https://1800562540-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LLfCoyr4-Jhfd18nMZ7%2F-LNjocW25V8qcyTaB-v3%2F-LNjsN6b1YewFgpxc_Hb%2FPasted%20Graphic%201.tiff?alt=media&amp;token=ea290061-3dfe-4b25-9528-bdab04622e97" alt="" data-size="original">
2. Adjancency-matrix representation (vertex-indexed array of lists) &#x20;

   <img src="https://1800562540-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LLfCoyr4-Jhfd18nMZ7%2F-LNjocW25V8qcyTaB-v3%2F-LNjsTEfNENojrrD7hRS%2FPasted%20Graphic.tiff?alt=media&amp;token=507e257b-20d6-4922-adf4-7d0c2c0d5005" alt="" data-size="original">

```java
 public class Graph {
   private final int V;
   private Bag<Integer>[] adj;
   public Graph(int V)
   {
      this.V = V;
      adj = (Bag<Integer>[]) new Bag[V];
      for (int v = 0; v < V; v++)
         adj[v] = new Bag<Integer>();
   }
   public void addEdge(int v, int w)
   {
      adj[v].add(w);
      adj[w].add(v);
   }
   public Iterable<Integer> adj(int v)
   {  return adj[v];  }
}
```

## &#x20;Depth First Search & Breadth First Search

Getting out of a maze.
