Hdu2952 Counting Sheep 【简单dfs】
http://acm.hdu.edu.cn/showproblem.php?pid=2952
题目大意:问图上有几堆羊。
直接dfs搜索。
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <cmath> #include <queue> using namespace std; template <class T> void checkmin(T &t,T x) {if(x < t) t = x;} template <class T> void checkmax(T &t,T x) {if(x > t) t = x;} template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;} template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;} typedef pair <int,int> PII; typedef pair <double,double> PDD; typedef long long ll; #define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++) int T , n , m; const int N = 111; bool vis[N][N]; char G[N][N]; int dir[4][2] = {1,0,0,1,-1,0,0,-1}; bool inmap(int x,int y) { return x >= 0 && y >= 0 && x < n && y < m; } void dfs(int x,int y) { vis[x][y] = 1; for(int i=0;i<4;i++) { int xx = x + dir[i][0] , yy = y + dir[i][1]; if(!inmap(xx,yy) || vis[xx][yy]) continue; if(G[xx][yy] == '#') dfs(xx,yy); } } int main() { scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); for(int i=0;i<n;i++) scanf("%s",G[i]); int ans = 0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) vis[i][j] = 0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) { if(!vis[i][j] && G[i][j] == '#') { ans ++; dfs(i , j); } } printf("%d\n" , ans); } return 0; }

浙公网安备 33010602011771号