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
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef vector<vector<int> > Pool; const int dx[] = {0,1,0,-1}; const int dy[] = {1,0,-1,0}; void dfs(Pool& pool,int x,int y){ pool[x][y]=0; for(int i = 0 ; i < 4 ; ++ i){ int newx = x+dx[i],newy = y+dy[i]; if(pool[newx][newy] == 1){ dfs(pool,newx,newy); } } } int main(){ int N; cin >> N; while(N--){ int m,n; cin >> m >> n; Pool pool(m+2,vector<int>(n+2,-1)); for(int i = 1; i <= m; ++ i){ for(int j = 1; j <= n; ++ j){ cin >> pool[i][j]; } } int res = 0; for(int i = 1; i <= m ; ++ i){ for(int j = 1 ; j <= n ; ++ j){ if(pool[i][j]==1){ res++; dfs(pool,i,j); } } } cout<<res<<endl; } }
原文:http://www.cnblogs.com/xiongqiangcs/p/3700832.html