2 Dec 2019

  • December 02, 2019
  • Amitraj
Graph Traversal

-> Graph traversal is a process of checking or updating each vertex in a graph.
-> It is also known as Graph Search.
-> Graph traversal means visiting each and exactly one node.
-> Tree traversal is a special case of graph traversal.

There are two techniques used in graph traversal-

1. Depth First Search (DFS)
2. Breadth First Search (BFS)



1. Depth First Search

-> Depth first search (DFS) is used for traversing a finite graph.

-> DFS traverses the depth of any particular path before exploring its breadth.

-> It explores one subtree before returning to the current node and then exploring the other subtree.

-> DFS uses stack instead of queue.

-> It traverses a graph in a depth-ward motion and gets the next vertex to start a search when a dead end occurs in any iteration.



/* C program to implement DFS (Depth first Search) */

#include<stdio.h>
void DFS(int i);
int visited[10],a[10][10],n;
int main()
{
int i,j;
printf("Enter number of Vertices:");
scanf("%d",&n);
printf("Enter adjacency matrix of the graph:");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d",&a[i][j]);
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("%d\t",i);
visited[i]=1;
for(j=0; j<n; j++)
if(visited[j]==0 && a[i][j]==1)
DFS(j);
}


OUTPUT:

Enter number of Vertices:5
Enter adjacency matrix of the graph:
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
1 0 0 0 0

0       1       2       3       4

Related Posts:

  • Directed and Undirected Graph in Data structure Directed Graph If a graph contains ordered pair of vertices, is said to be a Directed Graph. If an edge is represented using a pair of vertices (V1, V2), the edge is said to be directed from V1 to V2. The first element of… Read More
  • Merge Sort | Sorting Techniques in Data Structure Merge Sort -  -> Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms. -> Merge sort first divides… Read More
  • Graph Data Structure Graph Data Structure -> Graph is an abstract data type. -> A Graph is a non-linear data structure, is a collection of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines&nbs… Read More
  • Quick Sort | Sorting Techniques in Data Structure Quick sort -> Quick sort is an efficient sorting algorithm which is based on divide and conquer algorithm. In this sorting technique it picks a pivot value and divide the given array around the picked pivot. /* C progr… Read More
  • Heap Sort | Sorting Techniques in Data Structure Heap Sort -> In heap sort, heap removes the largest element from the end of partially sorted array. Reconstruct the heap after removing largest element & again remove the largest element from remaining elements and p… Read More

Translate

Popular Posts