Graphs Assignment
Graphs Assignment
Graphs Assignment
Algorithms
Labs Week 10 - Author: Paolo Falcarin
1. Graphs
Given the following directed graph, draw the adjacency list and draw the adjacency matrix:
Adjacency Matrix:
A B C D E F
A 0 1 0 0 0 0
B 0 0 1 0 0 0
C 0 0 0 0 1 0
D 0 1 0 0 0 0
E 0 0 0 1 0 1
F 0 0 0 0 0 0
Adjacency List:
AB
BC
CE
EDF
DB
2. More Graphs
Would you use the adjacency list structure or the adjacency matrix structure in the following
cases? Justify your choice.
2a. The graph has 10000 vertices and 20000 edges, and it is important to use as little space as
possible
Ans: In this case adjacency list structure is used as per me because adjacency matrix structure
takes a lot of space and results in memory wastage. Using Adjacency matrix structure will
result in 100,000,000 edges in graph but the graph has only 20000 edges.
So, adjacency list matrix is used for this.
2b. You need to answer whether two vertices of the graph are adjacent as fast as possible, no
matter how much space you use.
Ans:
The adjacency matrix is preferred here because we can check two edges are adjacent by
areAdjacent() operation in O(1) time irrespective of number of edges and nodes.
3. Graphs in Java
Download the CN5005-W10-Graph.zip eclipse project containing an implementation of the
Graph class and some text files representing different graphs.
The text files have the following format: the first line contains the number of nodes of the
graph and the type, and then each line represents a single edge, respectively identified by the
starting node, the ending node and the weight of the edge ( if no weight is specified then the
graph is unweighted).
For example, the edge going from A to B is represented by the line "A B 10", while if we
would add an edge of weight 7 from B to A the line would have been "B A 7".
5 5, directed
B D A B 10
AC3
A D 20
CB2
11 BD5
A
C E 15
D E 11
C E
}
2. int inDegree(String node): return the in-degree of a node in a di-graph.
5. boolean adjacent(String n1, String n2) return true if two nodes are adjacent, false
otherwise.