0% found this document useful (0 votes)
114 views10 pages

Classwork: Lab 9 Graph

This document provides information about representing and traversing graphs using different data structures. It discusses adjacency matrix, adjacency list, and edge list representations of graphs. It also explains breadth-first search and depth-first search graph traversal algorithms and provides code examples to implement them using adjacency matrix. The document is for a class on data structures and algorithms and provides guidance to students on exercises to complete.

Uploaded by

huy phan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views10 pages

Classwork: Lab 9 Graph

This document provides information about representing and traversing graphs using different data structures. It discusses adjacency matrix, adjacency list, and edge list representations of graphs. It also explains breadth-first search and depth-first search graph traversal algorithms and provides code examples to implement them using adjacency matrix. The document is for a class on data structures and algorithms and provides guidance to students on exercises to complete.

Uploaded by

huy phan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Ton Duc Thang University

Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

Lab 9
Graph
Quang D. C.
[email protected]

November 29, 2021

Note
In this lab, we will learn how to represent a graph on the computer:
• Adjacency Matrix
• Adjacency List
• Edge List
And two ways to traverse a graph:
• Breadth First Search (BFS)
• Depth First Search (DFS)

Part I
Classwork
In this part, lecturer will:

• Summarize the theory related to this lab.

• Instruct the lesson in this lab to the students.

• Explain the sample implementations.

Responsibility of the students in this part:

• Students practice sample exercises with solutions.

• During these part, students may ask any question that they don’t understand or
make mistakes. Lecturers can guide students, or do general guidance for the whole
class if the errors are common.

[email protected] 1
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

1. What is Graph?
Graph is the data structure that included vertices and edges. In other words, graph
is a set of vertices where some pairs of vertices are connected by edges.

Figure 1: Graph

We have three options to represent a graph:


• Adjacency Matrix
• Adjacency List
• Edge List

2. Representations of Graph
2.1. Adjacency Matrix (AM)
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in
a graph.
Let the 2D array be 𝑎𝑑𝑗[][], a slot 𝑎𝑑𝑗[𝑖][𝑗] = 1 indicates that there is an edge from
vertex 𝑖 to vertex 𝑗, otherwise 𝑎𝑑𝑗[𝑖][𝑗] contains 0.

Figure 2: Directed Graph

[email protected] 2
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

Adjacency matrix for undirected graph is always symmetric.

Figure 3: Undirected Graph

Adjacency Matrix is also used to represent weighted graphs. If 𝑎𝑑𝑗[𝑖][𝑗] = 𝑤, then


there is an edge from vertex 𝑖 to vertex 𝑗 with weight 𝑤.

Figure 4: Weighted Graph

You can create an AdjacencyMatrix class and define the code like this:
1 public class AdjacencyMatrix {
2 private int [][] adj;
3 private final int NUMBER_OF_VERTICES ;
4

5 public AdjacencyMatrix (int vertices ){


6 NUMBER_OF_VERTICES = vertices ;
7 adj = new int[ NUMBER_OF_VERTICES ][ NUMBER_OF_VERTICES ];
8 }
9
10 public void setEgde (int vertexSource , int vertexDestination ,
int weight ){
11 try {
12 adj[ vertexSource ][ vertexDestination ] = weight ;

[email protected] 3
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

13 adj[ vertexDestination ][ vertexSource ] = weight ;


14 } catch ( ArrayIndexOutOfBoundsException indexBounce ){
15 System .out. println ("The vertex is invalid ");
16 }
17 }
18
19 public int getEgde (int vertexSource , int vertexDestination ){
20 try{
21 return adj[ vertexSource ][ vertexDestination ];
22 } catch ( ArrayIndexOutOfBoundsException indexBounce ){
23 System .out. println ("The vertex is invalid ");
24 }
25 return -1;
26 }
27
28 public void printGraph (){
29 for(int i = 0; i < NUMBER_OF_VERTICES ; i++){
30 for(int j = 0;j < NUMBER_OF_VERTICES ; j++){
31 System .out. print (adj[i][j] + " ");
32 }
33 System .out. println ();
34 }
35 }
36 }

2.2. Adjacency List (AL)

Figure 5: Adjacency List

In Java, there are many collections that you can use to implement Adjacency List
like Vector, LinkedList, ArrayList, Map, ... Remember import java.util.* if you want
to use Java collections.
We use LinkedList to implement an AdjacencyList class (this code for the graph
without weights. If you want to handle weights, you can use Pair<Integer, Integer> in
Java instead of Integer):
1 import java.util .*;
2
3 public class AdjacencyList {
4 private int V; // No. of vertices
5 private LinkedList <Integer > adj [];
6

[email protected] 4
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

7 @SuppressWarnings (" unchecked ")


8 public AdjacencyList (int v)
9 {
10 V = v;
11 adj = new LinkedList [v];
12 for (int i=0; i<v; ++i)
13 adj[i] = new LinkedList <Integer >();
14 }
15
16 public void addEdge (int u, int v)
17 {
18 adj[u]. add(v);
19 }
20
21 public void printGraph (){
22 for(int i = 0; i < V; i++){
23 System .out. print (" Vertex " + i + ": ");
24 System .out. print ("head");
25 for( Integer v: adj[i]){
26 System .out. print ("->" + v);
27 }
28 System .out. println ();
29 }
30 }
31 }

2.3. Edge List (EL)

Figure 6: Edge List

There are many data structures to implement Edge List, this code use Vector and
class IntegerTriple, which is defined by user:
1 class IntegerTriple {
2 private Integer weight ;
3 private Integer source ;
4 private Integer dest;
5
6 public IntegerTriple ( Integer w, Integer s, Integer d){
7 weight = w;
8 source = s;

[email protected] 5
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

9 dest = d;
10 }
11
12 public Integer getWeight (){
13 return weight ;
14 }
15
16 public Integer getSource (){
17 return source ;
18 }
19
20 public Integer getDest (){
21 return dest;
22 }
23
24 @Override
25 public String toString (){
26 return weight + " " + source + " " + dest;
27 }
28 }
29
30 public class EdgeList {
31 private Vector < IntegerTriple > edges ;
32
33 public EdgeList (){
34 edges = new Vector < IntegerTriple >();
35 }
36

37 public void addEdge (int w, int u, int v){


38 edges .add(new IntegerTriple (w,u,v));
39 }
40
41 public void printGraph (){
42 for(int i = 0; i < edges .size (); i++){
43 System .out. println ( edges .get(i));
44 }
45 }
46 }

3. Graph traversal algorithms


3.1. Breadth First Search (BFS)
Review the BFS algorithm that you learned in your theory class. Mapping it to the
following code (this code is implemented for Adjacency Matrix):
1 public void BFS(int s){
2 boolean visited [] = new boolean [ NUMBER_OF_VERTICES ];
3
4 Queue <Integer > queue = new LinkedList <Integer >();
5
6 visited [s] = true;
7 queue .add(s);
8
9 while (! queue . isEmpty ()){

[email protected] 6
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

10 int x = queue .poll ();


11 System .out. print (x + " ");
12
13 for(int i = 0; i < NUMBER_OF_VERTICES ; i++){
14 if(adj[x][i] != 0 && visited [i] == false ){
15 queue .add(i);
16 visited [i] = true;
17 }
18 }
19 }
20 }

3.2. Depth First Search (DFS)


Review the recursion DFS algorithm that you learned in your theory class. Mapping
it to the following code (this code is implemented for Adjacency Matrix):
1 public void DFS_recur (int v, boolean [] visited ){
2 visited [v] = true;
3
4 System .out. print (v + " ");
5
6 for(int i = 0; i < NUMBER_OF_VERTICES ; i++){
7 if(adj[v][i] != 0 && visited [i] == false ){
8 DFS_recur (i, visited );
9 }
10 }
11 }
12

13 public void DFS(int s){


14 boolean [] visited = new boolean [ NUMBER_OF_VERTICES ];
15 DFS_recur (s, visited );
16 }

Part II
Excercise
Responsibility of the students in this part:

• Complete all the exercises with the knowledge from Part I.

• Ask your lecturer if you have any question.

• Submit your solutions according to your lecturer requirement.

Exercise 1
A graph is saved to file in AM format: (see the picture below)

(a) Read the graph from the file and print the AM on the screen.

[email protected] 7
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

(b) Count the number of vertices.

(c) Count the number of edges.

(d) Enumerate neighbors of a vertex u.

(e) Check the existence of edge (u, v).

Exercise 2
A graph is saved to file in AL format: (see the picture below)

(a) Read the graph from the file and print the AL on the screen.

(b) Count the number of vertices.

(c) Count the number of edges.

(d) Enumerate neighbors of a vertex u.

(e) Check the existence of edge (u, v).

[email protected] 8
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

Exercise 3
A graph is saved to file in EL format: (see the picture below)

(a) Read the graph from the file and print the EL on the screen.

(b) Count the number of vertices.

(c) Count the number of edges.

(d) Enumerate neighbors of a vertex u.

(e) Check the existence of edge (u, v).

Exercise 4
Choose a graph, and use Adjacency Matrix to represent it. Implement the functions
for the below requirements:

(a) Traverse the graph by using BFS. Print the traversal result on the screen.

(b) Traverse the graph by using DFS. Print the traversal result on the screen.

(c) Implement the DFS method without recursion. Print the traversal result on the
screen.(Hint: using Stack)

(d) Implement the IsReachable method to test whether vertex v is reachable from vertex
u.

[email protected] 9
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022

Exercise 5
Write a method in the AdjacencyMatrix class to convert a graph from Adjacency
Matrix to Adjacency List.
1 public AdjacencyList convertToAL (){
2 ...
3 }
THE END

[email protected] 10

You might also like