Problem Type : Graph Using BFS Algorithm
#include<stdio.h>
#include<string.h>
#define max 1000
int mat[max][max];
int cost[max],color[max],queue[max];
void bfs(int node,int start)
{
int front,rear,i,u,c;
front = rear = 0;
queue[rear ++] = start;
color[start] = 1;
c=0;
while(front!=rear)
{
u = queue[front++];
for(i=0; i<node; i++)
{
if(mat[u][i] && !color[i])
{
color[i]=1;
queue[rear++] = i;
cost[i] = cost[u]+1;
c++;
}
}
}
for(i=0; i<=c; i++)
{
if(cost[i]!=0)
printf("%d\n",cost[i]);
}
return ;
}
int main()
{
int node,edge,i,n,m,start,c,t,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&node,&edge);
for(i=0; i<edge; i++)
{
scanf("%d%d",&n,&m);
mat[n][m] = 1;
mat[m][n] = 1;
}
start =0;
bfs(node,start);
memset(color,0,sizeof(color));
memset(cost,0,sizeof(cost));
memset(mat,0,sizeof(mat));
memset(queue,0,sizeof(queue));
if(t>0)
printf("\n");
}
return 0;
}
#include<stdio.h>
#include<string.h>
#define max 1000
int mat[max][max];
int cost[max],color[max],queue[max];
void bfs(int node,int start)
{
int front,rear,i,u,c;
front = rear = 0;
queue[rear ++] = start;
color[start] = 1;
c=0;
while(front!=rear)
{
u = queue[front++];
for(i=0; i<node; i++)
{
if(mat[u][i] && !color[i])
{
color[i]=1;
queue[rear++] = i;
cost[i] = cost[u]+1;
c++;
}
}
}
for(i=0; i<=c; i++)
{
if(cost[i]!=0)
printf("%d\n",cost[i]);
}
return ;
}
int main()
{
int node,edge,i,n,m,start,c,t,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&node,&edge);
for(i=0; i<edge; i++)
{
scanf("%d%d",&n,&m);
mat[n][m] = 1;
mat[m][n] = 1;
}
start =0;
bfs(node,start);
memset(color,0,sizeof(color));
memset(cost,0,sizeof(cost));
memset(mat,0,sizeof(mat));
memset(queue,0,sizeof(queue));
if(t>0)
printf("\n");
}
return 0;
}
No comments:
Post a Comment