Undirected Graph
| 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 0 | 0 |
| 2 | 1 | 0 | 1 | 0 | 1 |
| 3 | 1 | 1 | 0 | 1 | 0 |
| 4 | 0 | 0 | 1 | 0 | 1 |
| 5 | 0 | 1 | 0 | 1 | 0 |
Directed Graph
| 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 0 | 0 | 0 |
| 2 | 1 | 0 | 0 | 0 | 1 |
| 3 | 1 | 1 | 0 | 0 | 0 |
| 4 | 0 | 0 | 1 | 0 | 0 |
| 5 | 0 | 0 | 0 | 1 | 0 |
Directed Graph + weight on edges
(unweight => weight = 1)
| 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| 1 | ? | ? | ? | ? | ? |
| 2 | ? | 6 | ? | ? | -3 |
| 3 | 4 | -1 | ? | ? | ? |
| 4 | ? | ? | 5 | ? | ? |
| 5 | ? | ? | ? | 2 | ? |
Undirected Graph
| 1 | 2 | 3 | ||
| 2 | 1 | 3 | 5 | |
| 3 | 1 | 2 | 4 | |
| 4 | 3 | 5 | ||
| 5 | 2 | 4 |
each vertex stores a list of its neighbors
(one of the implementations: linked-list)
Directed Graph
| 1 | ||||
| 2 | 1 | 5 | ||
| 3 | 1 | 2 | ||
| 4 | 3 | |||
| 5 | 4 |
Directed Graph + weight on edges
in u's list we store (v, cost)
| 1 | ||||
| 2 | (1, 6) | (5, -3) | ||
| 3 | (1, 4) | (2, -1) | ||
| 4 | (3, 5) | |||
| 5 | (4, 2) |
| Adjacency Matrix | Adjacency List | |
|---|---|---|
| Space Complexity |
||
| Ask if there is an edge between two node | ||
| Iterate every edge of a node |
Similiar with DFS, BFS on tree
Main cause of RE, TLE
Code of DFS((adjacency matrix)
const int n = 10000;
int G[n][n]; // edge index;
bool visited[n];
void init()
{
for(int u = 0; u < n; u++)
visited[u] = false;
}
void addEdge(int u, int v)
{
G[u][v] = 1;
G[v][u] = 1;
}
void DFS(int u)
{
visited[u] = true;
for(int v = 0; v < n; v++)
{
if(G[u][v] == 1)
{
if(visited[v] == false)
DFS(v);
}
}
}
Code of DFS(adjacency list)
const int n = 10005
vector<int> G[n]; // adjacency list
bool visited[n];
void init()
{
for(int u = 0; u < n; u++)
{
visited[u] = false;
}
}
void addEdge(int u, int v)
{
G[u].push_back(v);
G[v].push_back(u); // if undirected
}
void DFS(int u)
{
visited[u] = true;
for(int i = 0; G[u].length(); i++)
{
int v = G[u][i];
if(visited[v] == false)
{
DFS(v);
}
}
}Code of BFS
void bfs(int v){
queue<int> tv; // tovisited
tv.push(v);
while(!tv.empty())
{
int u = tv.top();
tv.pop();
for(int i = 0; i < G[u].size(); i++){
if(visited[G[u][i]])
continue;
visited[G[u][i]] = true;
tv.push(G[u][i]);
}
}
// G[v] is a array store all neighbor of a vertex v
}After a single round of DFS, all vertices in the same c.c will be visited.
In contrast, vertices that aren't in the same c.c. won't be visited.
After a single round of DFS, all vertices in the same c.c will be visited.
In contrast, vertices that aren't in the same c.c. won't be visited.
We can just count how many rounds DFS it takes to visit all vertices!
int cnt = 0; // count
for(int i = 0; i < V; i++) // 0 ~ V-1
{
visited[i] = false;
}
for(int i = 0; i < V; i++){
if(!visited[i]){
dfs(i);
cnt++;
}
}Homework