UVa 572

就是求一个无向图的联通分支的个数。水题

我是这么求的:

用一个visited全局数组来标识某个点是否被访问过,如果一个联通分支中的一个被访问,则该联通分支中的节点必然全部被访问,对所有节点遍历一遍,每次都深搜,如果此节点的visited为假,则说明它属于一个新的联通分支,计数器加一,代码如下~

#include<stdio.h>
char map[200][200];
int visited[200][200];
int direction[8][2]=
{
{-1,0},{-1,-1},{-1,+1},{0,1},{0,-1},{1,-1},{1,0},{1,1}
};
int row,column;
int count;
struct point
{
int x;
int y;
};
void DFS(int x,int y)
{

point * stack=new point[5000];
point temp;
int top=-1;
int tx=x;
int ty=y;
top++;
stack[top].x=x;
stack[top].y=y;
while(top!=-1)
{
temp=stack[top--];
visited[temp.x][temp.y]=1;
for(int i=0;i<8;++i)
{
tx=temp.x;
ty=temp.y;
tx+=direction[i][0];
ty+=direction[i][1];
if(tx>=0&&tx<row&&ty>=0&&ty<column&&visited[tx][ty]==0&&map[tx][ty]!='*')
{
++top;
stack[top].x=tx;
stack[top].y=ty;
visited[tx][ty]=1;
}
}
}
delete[]stack;
}
int main()
{
while(scanf("%d%d",&row,&column)!=EOF)
{
for(int i=0;i<row;++i)
for(int j=0;j<column;++j)
{
visited[i][j]=0;
}
count=0;
if(row==0&&column==0)
return 0;
getchar();
for(int i=0;i<row;++i)
{
gets(map[i]);

for(int i=0;i<row;++i)
{
for(int j=0;j<column;++j)
{
if(visited[i][j]==0&&map[i][j]=='@')
{
count++;
DFS(i,j);
}
}
}
printf("%d\n",count);
}
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值