0% found this document useful (0 votes)
18 views5 pages

Sumit

Uploaded by

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

Sumit

Uploaded by

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

PROGRAM - 13

Q13- Implementation of BFS


#include <stdio.h>

int i, n, j, front = 0, queue[10], rear = -1, visited[10];


int a[10][10];
void bfs(int v)

queue[++rear] = v;
visited[v] = 1;
while (front <= rear)
{ v = queue[front+
+]; printf(" %d ",
v);
for (i = 0; i < n; i++) {

if (a[v][i] && !visited[i])


{ queue[++rear] = i;
visited[i] = 1;

int main()

{
int v;

printf("Enter the number of vertices: ");


scanf("%d", &n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
{
scanf("%d", &a[i][j]);

}
for (i = 0; i < n; i++) {
visited[i] = 0;
}

printf("Enter the starting vertex: ");


scanf("%d", &v);
bfs(v);
return 0;
}

OUTPUT:
PROGRAM - 14
Q14- Implementation of DFS
#include <stdio.h>

#define MAX_NODES 100


int top = -1;
int stack[MAX_NODES];
void push(int node)
{

stack[++top] = node;

int pop()

return stack[top--];

}
void dfs(int adjMatrix[MAX_NODES][MAX_NODES], int nodes, int startNode)

int visited[MAX_NODES] = {0};

printf("DFS Traversal starting from node %d: ",


startNode); push(startNode);
visited[startNode] = 1;
while (top != -1) {
int currentNode = pop();
printf("%d ", currentNode);
for (int i = 0; i < nodes; ++i) {

if (adjMatrix[currentNode][i] && !visited[i]) {


push(i);
visited[i] = 1;

printf("\n");
}

int main(){

int nodes, i, j;

printf("Enter the number of nodes: ");


scanf("%d", &nodes);
int adjMatrix[MAX_NODES][MAX_NODES] = {0};
printf("Enter the adjacency matrix (0 or 1):\n");
for (i = 0; i < nodes; ++i) {
for (j = 0; j < nodes; ++j) {
scanf("%d", &adjMatrix[i][j]);

int startNode;

printf("Enter the starting node for DFS: ");


scanf("%d", &startNode);
dfs(adjMatrix, nodes, startNode);
return 0;
}
OUTPUT:

You might also like