标签:main other 学院 namespace play ring -- out problem
2 3 4 1 0 0 0 0 0 1 1 1 1 1 0 5 5 1 1 1 1 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1
2 3
1 #include <iostream> 2 3 using namespace std; 4 5 char pos[100][100]; 6 int n,m; 7 void dfs(int x, int y) 8 { 9 if(0<=x&&x<n&&0<=y&&y<m&&pos[x][y]==‘1‘) 10 { 11 pos[x][y] = ‘0‘; 12 dfs(x-1,y); 13 dfs(x+1,y); 14 dfs(x,y-1); 15 dfs(x,y+1); 16 } 17 return ; 18 } 19 int main(void) 20 { 21 int t; 22 cin>>t; 23 while(t--) 24 { 25 cin>>n>>m; 26 for(int i = 0; i < n; i++) 27 for(int j = 0; j < m; j++) 28 cin>>pos[i][j]; 29 int count = 0; 30 for(int i = 0;i < n; i++) 31 for(int j = 0;j < m; j++) 32 { 33 if(pos[i][j] == ‘1‘) 34 { 35 dfs(i,j); 36 count++; 37 } 38 } 39 cout<<count<<endl; 40 } 41 return 0; 42 }
采用深度优先遍历可以解决,根据题目要求,假设从任意一点值为‘1‘的出发,将这点的坐标上下左右全部用‘0‘替换,1次DFS后与初始动这个‘1‘连接的‘1‘全部被替换成‘0‘,因此,直到图中不再存在‘1‘为至,总共进行的DFS的次数就是最后的结果
另一种
#include<stdio.h>
#include<string.h>
int s,t,a[101][101];
int dx[4]={0,0,1,-1};//**四个方向搜索**//
int dy[4]={1,-1,0,0};
void bfs(int x,int y)
{
a[x][y]=0;
for(int k=0;k<4;k++)
{
s=x+dx[k];
t=y+dy[k];
if(a[s][t]==1)
{
bfs(s,t);
}
}
}
int main()
{
int ncases,n,m,i,j,count;
scanf("%d",&ncases);
while(ncases--)
{
count=0;
scanf("%d %d",&n,&m);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(a[i][j]==1)
{
bfs(i,j);
count++;
}
}
}
printf("%d\n",count);
}
return 0;
}
标签:main other 学院 namespace play ring -- out problem
原文地址:http://www.cnblogs.com/521LOVE/p/7400194.html