summaryrefslogtreecommitdiff
path: root/doc/unit/12/README.md
blob: 66a4b6d029a0555941914a6635ba3f88a32f5851 (plain)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# Graphs

## Directed graph

```plaintext
G = (V,E) where
* V is a set of vertices
* E is a set of ordered pairs of vertices called edges
```

An edge `(i, j)` is directed from `i` to `j`;

* `i` is the source
* `j` is the target

A `path` in `G` is a sequence of vertices.

Typical operations:

* `addEdge(i,j)`: Add the edge (i, j) to E. `O(1)` time.
* `removeEdge(i,j)`: Remove the edge `(i, j)` from E. `O(1)` time.
* `hasEdge(i, j)`: Check if the edge `(i, j)` is an element of E. `O(1)` time.
* `outEdges(i)`: Return a `List` of all ints `j` such that `(i,j)` is an element of E. `O(n)` time.
* `inEdges(i)`: Return a `List` of all ints `j` such that `(j,i)` is an element of E. `O(n)` time.

`O(n^2)` space.

### AdjacencyMatrix: Representing a Graph by a Matrix

Is a way of representing an `n` vertex graph `G = (V,E)`
by an `n x m` matrix, `a`, whose entries are boolean values.

```java
int n;
boolean[][] a;

AdjacencyMatrix(int nO) {
  n = nO;
  a = new boolean[n][n];
}
```

The matrix entry `a[i][j]` is defined as:

```plaintext
a[i][j] = { true if (i, j) element of E otherwise false
```

```java
void addEdge(int i, int j) {
  a[i][j] = true;
}

void removeEdge(int i, int j) {
  a[i][j] = false;
}

boolean hasEdge(int i, int j) {
  return a[i][j];
}

List<Integer> outEdges(int i) {
  List<Integer> edges = new ArrayList<Integer>();
  for (int j = 0; j < n; j++)
    if (a[i][j])
      edges.add(j);
  return edges;
}

List<Integer> inEdges(int i) {
  List<Integer> edges = new ArrayList<Integer>();
  for (int j = 0; j < n; j++)
    if (a[j][i])
      edges.add(j);
  return edges;
}
```

It is large. It stores `n x n` boolean matrix, so it requires
at least `n^2` bits of memory.

### AdjacencyLists: A Graph as a Collection of Lists

representations of graphs take a more vertex-centric approach.
There are many possible implementations of adjacency lists.

Operations:

* `addEdge(i, j)`: `O(1)` time
* `removeEdge(i, j)`: `O(deg(1))` time
* `hasEdge(i, j)`: `O(deg(1))` time
* `outEdges(i)`: in `O(1)` time
* `inEdges(i)`: in `O(n + m)` time

`O(n + m)` space.


```java
int n;
List<Integer>[] adj;

AdjacencyLists(int nO) {
  n = nO;
  adj = (List<Integer>[])new List[n];
  for (int i = 0; i < n; i++)
    adj[i] = new ArrayStack<Integer>();
}

void addEdge(int i, int j) {
  adj[i].add(j);
}

void removeEdge(int i, int j) {
  Iterator<Integer> it = adj[i].iterator();
  while (it.hasNext()) {
    if (it.next() == j) {
      it.remove();
      return;
    }
  }
}

boolean hasEdge(int i, int j) {
  return adj[i].contains(j);
}

List<Integer> outEdges(int i) {
  return adj[i];
}

List<Integer> inEdges(int i) {
  List<Integer> edges = new ArrayStack<Integer>();
  for (int j = 0; j < n; j++)
    if (adj[j].contains(i))
      edges.add(j);
  return edges;
}
```

## Graph Traversal

### Breadth-First Search

starts at a vertex `i` and visits, first the neighbours of `i`,
then the neighbours of the neighbours of `i`, then the
neighbours of the neighbours of the neighbours of `i`, and so on.

It uses a `queue` and makes sure that the same vertex is
not added more than once. It does this be keep track of each 
vertex that has been visited.

```java
void bfs(Graph g, int r) {
  boolean[] seen = new boolean[g.nVertices()];
  Queue<Integer> q = new SLList<Integer>();
  q.add(r);
  seen[r] = true;
  while (!q.isEmpty()) {
    int i = q.remove();
    for (Integer j : g.outEdges(i)) {
      if (!seen[j]) {
        q.add(j);
        seen[j] = true;
      }
    }
  }
}
```

time complexity: when using an adjacency list `O(n+m)`.

BFS is useful for computing shortest paths.

### Depth-First Search

is similar to the standard algorithm for traversing binary trees.
It fully explores one subtree before returning to the current
node and then exploring the other subtree. Another way to
think of depth-first search is by saying that it is similar
to breadth-first search except that it uses a stack instead
of a queue.

Each node has a state:

* not visited
* visited
* visiting

Think of it as a recursive algorithm.

```java
void dfs(Graph g, int r) {
  byte[] c = new byte[g.nVertices()];
  dfs(g, r, c);
}

// uses recursive stack
void dfs(Graph g, int i, byte[] c) {
  c[i] = grey;
  for (Integer j : g.outEdges(i)) {
    if (c[j] == white) {
      c[j] = grey;
      dfs(g, j, c);
    }
  }
  c[i] = black;
}

void dfs2(Graph g, int r) {
  byte[] c = new byte[g.nVertices()];
  Stack<Integer> s = new Stack<Integer>();
  s.push(r);

  while (!s.isEmpty()) {
    int i = s.pop();
    if (c[i] == white) {
      c[i] = grey;
      for (int j : g.outEdges(i))
        s.push(j);
    }
  }
}
```

time complexity: when using an adjacency list `O(n+m)` time.