Unit 12
Unit 12
Graphs
Generally, no restriction is imposed on the number of nodes in the graph or on the connections one node
can have to other nodes.
Graph Applications
Modeling routs between cities. Modeling flights between airports.
V = {A,B,C,D}
E = {(A,B),(A,C),(C,B),(C,D),(B,D)}
If two nodes are connected by an edge, they are neighbors (and the nodes are adjacent to each other)
example A,B or A,C
The degree of a node is the number of edges it has, example degree of node A is 2
Graph types
This weight might represent the length of the route, the cost, the energy required to move between the two
locations, etc.
public Graph()
{
vertexList = new Vertex[MAX_VERTS];
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++)
for(int k=0; k<MAX_VERTS; k++)
adjMat[j][k] = 0;
}
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
// ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
// ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
}
Graph Implementation
2) Adjacency List
Dijkstra’s Algorithm
The solution for the shortest-path problem is called Dijkstra’s
algorithm, after Edsger Dijkstra, who first described it in 1959.
The algorithm used with weighted graph.
2
1 5
2
3
3
S={1}
1
2 3
1 6
V = { 1, 2, 3, 4, 5, 6, 7}
3 3 2
3
V – S = { 2, 3, 4, 5, 6, 7 }
4 7
1
1 2 3 4 5 6 7
0 3 2 3 ∞ ∞ ∞
Dijkstra’s Algorithm Operation
2
1 5
2
3
3
S = { 1, 3 }
1
2 3
1 6
V – S = { 2, 4, 5, 6, 7 }
3 3 2
3
4 7
1
1 2 3 4 5 6 7
0 3 2 3 ∞5 ∞3 ∞
Dijkstra’s Algorithm Operation
2
1 5
2
3
3
S = { 1, 3, 4 }
1
2 3
1 6
V – S = { 2, 5, 6, 7 }
3 3 2
3
4 7
1
1 2 3 4 5 6 7
0 3 2 3 5 3 ∞4
Dijkstra’s Algorithm Operation
2
1 5
2
3
3
S = { 1, 3, 4, 2 }
1
2 3
1 6
V – S = { 5, 6, 7 }
3 3 2
3
4 7
1
1 2 3 4 5 6 7
0 3 2 3 54 3 4
Dijkstra’s Algorithm Operation
2
1 5
2
3
3
S = { 1, 3, 4, 2, 6 }
1
2 3
1 6
V – S = { 5, 7 }
3 3 2
3
4 7
1
1 2 3 4 5 6 7
0 3 2 3 4 3 4
Dijkstra’s Algorithm Operation
2
1 5
2
3
3
S = { 1, 3, 4, 2, 6, 7 }
1
2 3
1 6
V–S={5}
3 3 2
3
4 7
1
1 2 3 4 5 6 7
0 3 2 3 4 3 4
Dijkstra’s Algorithm Operation
2
1 5
2
3
3
S = { 1, 3, 4, 2, 6, 7, 5 }
1
2 3
1 6
V–S={ }
3 3 2
3
4 7
1
1 2 3 4 5 6 7
0 3 2 3 4 3 4