DFS
Coding Problem Keys
DFS
Problem Statement
An N*N matrix representation of a graph is given as input, where 1 at Mth row and Nth the column denotes node M and node N are connected directly. A 0 denotes the two nodes are disconnected. Perform a depth-first traversal and print the nodes in the traversing order. When visiting the neighboring node, the priority must be given to the node with least value to visit first.
Boundary Condition(s)
1 <= N <= 100
Input Format
The first line contains the value of N and source node separated by space(s).
The next N lines contain N elements each separated by space(s).
Output Format
The first line contains nodes separated by a space.
Example Input/Output 1
Input
5 1
1 1 1 0 1
1 1 0 1 0
1 0 1 1 1
0 1 1 1 1
1 0 1 1 1
Output
1 2 4 3 5
Example Input/Output 2
Input
4 1
1 0 1 0
0 1 1 1
1 1 1 0
0 1 1 1
Output
1 3 2 4
Solution
Programming Language: C Language
#include<stdio.h>
#include<stdlib.h>
void DFS(int);
int g[100][100],visited[100],n,start;
void main(){
int i,j;
scanf("%d",&n);
scanf("%d",&start);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&g[i][j]);
for(i=1;i<=n;i++)
visited[i]=0;
DFS(start);
}
void DFS(int i){
int j;
printf("%d ",i);
visited[i]=1;
for(j=1;j<=n;j++)
if(!visited[j]&&g[i][j]==1)
DFS(j);
}
// Published By PKJCODERS
Alter
#include<stdio.h>
#include <stdlib.h>
int n,l[101][101],k=0,p=0;
int app(int c){
if(p>k)
return 0;
int i,ii;
for(i=0;i<n;i++){
if(l[c][i]==1 && i!=c){
printf("%d ",i+1);
l[c][i]=-1;
k++;
for(int q=0;q<n;q++)
l[q][i]=-1;
app(i);}
}
return 0;
}
int main(){
int c,i,j,t=0;
scanf("%d %d\n",&n,&c);
for(i=0;i<n;i++){
for(j=0;j<n;j++)
scanf("%d ",&l[i][j]);
scanf("\n");
}
c=c-1;
printf("%d ",c+1);
for(int qq=0;qq<n;qq++)
l[qq][c]=-1;
app(c);
return 0;
}
// Published By PKJCODERS
(Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.)
Comments