0% found this document useful (0 votes)
35 views

Topic 5 Graphs

A graph is composed of vertices and edges. It can be represented using an adjacency matrix or adjacency list. Common graph algorithms like BFS, DFS, Dijkstra's algorithm are used to traverse and find shortest paths in graphs.

Uploaded by

temporal034
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)
35 views

Topic 5 Graphs

A graph is composed of vertices and edges. It can be represented using an adjacency matrix or adjacency list. Common graph algorithms like BFS, DFS, Dijkstra's algorithm are used to traverse and find shortest paths in graphs.

Uploaded by

temporal034
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/ 30

Engineering School

Computer Architecture and Operating Systems Department

Degree: Artificial Intelligence


Subject: Fundamentals of Programming II

Graphs
Graphs

Graphs vs graphs

Graphs – charts Graphs – descrete mathematics


Graphs

A Graph is a non-linear data structure consisting of


vertices and edges.

The vertices are sometimes also referred to as nodes


and the edges are lines or arcs that connect any two
nodes in the graph.

More formally a Graph is composed of a set of vertices


(V) and a set of edges(E).

The graph is denoted by G(E, V).

https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/
Graphs

Components of a Graph
Vertices:
Vertices are the fundamental units of the graph. Sometimes,
vertices are also known as vertex or nodes. Every
node/vertex can be labeled or unlabelled.

Edges:
Edges are drawn or used to connect two nodes of the graph.
It can be ordered pair of nodes in a directed graph. Edges can
connect any two nodes in any possible way. There are no
rules. Sometimes, edges are also known as arcs. Every edge
can be labeled/unlabelled.
Graphs

https://neo4j.com/blog/graphs-for-artificial-intelligence-and-machine-learning/
Graphs
Types

Labeled
labels (which are most commonly numbers) are assigned to nodes/edges.

Nonlabeled
individual nodes have no distinct identifications except through
their interconnectivity.

Directed
edges have a direction. The edges indicate a one-way relationship, in that
each edge can only be traversed in a single direction.

Undirected (bidirected)
edges do not have a direction. The edges indicate a two-way relationship, in
that each edge can be traversed in both directions.
Graphs
Sequential representation - Adjacency matrix
a square matrix used to represent a finite graph.

The elements of the matrix indicate whether


pairs of nodes are adjacent or not in the graph.

https://www.geeksforgeeks.org/add-and-remove-edge-in-adjacency-matrix-representation-
of-a-graph/
Graphs
Linked list representation - Adjacency list
An adjacency list is used in the linked representation to store the
graph

The index of the array represents a node and each element in its
linked list represents the other nodes that form an edge with the
node.

It is efficient in terms of storage as we only have to store the values


for edges.
Graphs

A weighted graph

a graph in which each edge is given a numerical weight.

In the case that the edges have associated numerical information that
represents the cost necessary to traverse that edge, we will say that the
graph is weighted.
Coruña Oviedo 304
Bilbao
171

45
5

32
0
28

Vigo 356 Girona


Gerona
4
Zaragoza 0
39 5

296 10
5 Barcelona
19

Valladolid 32
3

9
34
Madrid
3 25
40 1
19 1 Valencia
3 35

Badajoz
241
1 50

Jaén
2
24
99

Sevilla Murcia
256 278
5
12

Cádiz Granada
Graphs

Adjacency matrix for weighted graphs

The elements of the matrix indicate the cost between


nodes
Graphs

Search

Expand each node it finds, recursively, by traversing all nodes on a


particular path.

When there are no more nodes left to visit on this path, a step back
(backtracking) is performed, to start the same process with each of
the adjacent nodes of the current node that has already been
processed.
Graphs
BFS Breadth First Search (level order traversal)
The Queue data structure is used for the Breadth First Search traversal.

When we use the BFS algorithm for the traversal in a graph, we can
consider any node as a root node.

DFS Depth First Search


The Stack data structure is used, which works on the LIFO (Last In First
Out) principle.

Traversing can be started from any node, or we can say that any node
can be considered as a root node until the root node is not mentioned in
the problem.
Graphs
BFS
The element which is deleted from the Queue, the adjacent nodes of
the deleted node are added to the Queue.

A standard BFS implementation puts each node of the graph into one
of two categories:
• Visited
• Not Visited

create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited) neighbours of u

https://www.programiz.com/dsa/graph-bfs
Graphs
BFS

create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited) neighbours of u

https://www.programiz.com/dsa/graph-bfs
Graphs
DFS
The element which is removed from the stack, then only one adjacent
node of a deleted node is added in the stack.

A standard DFS implementation puts each node of the graph into one
of two categories:
• Visited
• Not Visited

DFS(G, u)
u.visited = true
for each v ∈ G.Adj[u]
if v.visited == false
DFS(G,v)

https://www.programiz.com/dsa/graph-dfs
Graphs
DFS

DFS(G, u)
u.visited = true
for each v ∈ G.Adj[u]
if v.visited == false
DFS(G,v)

Stack

https://www.programiz.com/dsa/graph-dfs
Graphs
Example

BFS -> {A B S C G D E F H}

DFS -> {A B S C D E H G F}
Graphs
Dijkstra algorithm - shortest path

EDSGER WYBE DIJKSTRA – 11.05.1930 – 06.08.2002


Received the 1972 A. M. Turing Award, widely considered the most
prestigious award in computer science.

"Computer Science is no more about computers than


astronomy is about telescopes."
Given a graph and a source vertex in the graph,
it finds the shortest paths between nodes in a weighted graph (road
networks)

https://en.wikipedia.org/wiki/Dijkstras_algorithm
Graphs
Dijkstra algorithm - shortest path

It picks the unvisited vertex with the lowest distance, calculates the distance
through it to each unvisited neighbor, and updates the neighbor's distance
if smaller.

1. Mark your selected initial node with a current distance of 0


and the rest with infinity.
2. Set the non-visited node with the smallest current distance as
the current node C.
3. For each neighbour N of your current node C: add the current
distance of C with the weight of the edge connecting C-N. If
it's smaller than the current distance of N, set it as the new
current distance of N.
4. Mark the current node C as visited.
5. If there are non-visited nodes, go to step 2.

https://en.wikipedia.org/wiki/Dijkstras_algorithm
Graphs

Dijkstra algorithm

https://www.programiz.com/dsa/dijkstra-algorithm
Graphs

Dijkstra algorithm

• (s1,1), (s2,3)
• (s2,3), (s4,5), (s3,9)
• (s4,5), (s3,9)
• (s5,6), (s3,9)
• (s3,7), (t,16)
• (t,14)

Shortest path: s, s1, s4, s5, s3, t;


Cost:14
Graphs

The minimum distance from 0 to 1 = 4.


The minimum distance from 0 to 2 = 12. 0->1->2
The minimum distance from 0 to 3 = 19. 0->1->2->3
The minimum distance from 0 to 4 = 21. 0->7->6->5->4
The minimum distance from 0 to 5 = 11. 0->7->6->5
The minimum distance from 0 to 6 = 9. 0->7->6
The minimum distance from 0 to 7 = 8. 0->7
The minimum distance from 0 to 8 = 14. 0->1->2->8
Graphs
Different scenarios:
It contains number of nodes
struct Graph graph; and the graph representation

- if we have a given adjacency matrix, e.g.:


adjMatrix[N][N]; //static array (global)

- If have to create from scratch adjacency matrix, e.g.:


int ** adjMatrix; //dynamic 2D array (malloc)
adjMatrix[i][j];

int * adjMatrix; //dynamic 1D array (malloc)


adjMatrix[i*N+j];

- If we base our solution on adjacency list and we have to create a


corresponding graph, e.g.:
struct node ** adjList; // array of pointers to nodes
Graphs
struct Graph
{
int numNodes;
struct node **adjList;
int *visited; different if we have adjMatrix[][];
};

struct node
{
int data;
};
Graphs
Examples of basic operations:
struct Graph * CreateGraph(int numNodes);

void DestroyGraph (struct Graph * g);

void PrintGraph(struct Graph * g);

void AddEdge (struct Graph * g, int src, int dest);


Graphs
int main (...)
{
struct Graph * g = createGraph (4);

AddEdge (g, 0, 1);


AddEdge (g, 0, 2);
AddEdge (g, 1, 2);
AddEdge (g, 2, 3);

printGraph (g);
}
Graphs
struct Graph * createGraph (int numNodes)
{
struct Graph * graph=malloc(sizeof(struct Graph));
graph->numNodes=numNodes;
graph->visited=malloc(numNodes*sizeof(int));

//1D dynamic matrix
graph->adjMatrix=malloc(numNodes*numNodes*sizeof(int));

//or 2D dynamic matrix


graph->adjMatrix=malloc(numNodes*sizeof(int*));

for (int i=0; i<numNodes; i++)


{
graph->adjMatrix[i]=malloc(numNodes*sizeof(int));
graph->visited[i]=0;
}
...
return graph;
}
Graphs
//matrix
void AddEdge(struct Graph *g, int src, int dest)
{
g->adjMatrix[src][dest] = 1;
g->adjMatrix[dest][src] = 1;
}

//list
void AddEdge(struct Graph * g, int src, int dest)
{
//one direction, new node added at the beginning of the list
struct node * newNode = createNode(dest);
newNode->next = g->adjList[src];
g->adjList[src] = newNode;

//two directions
/*newNode = createNode(src);
newNode->next = g->adjList[dest];
g->adjList[dest] = newNode;*/
}
Graphs
BFS
struct QueueNode struct QueueNode *first;
{
int data; struct QueueNode *last;
struct QueueNode *next;
};

DFS
struct StackNode struct StackNode *top;
{
int data;
struct StackNode *next;
};

You might also like