经典搜索水题......
#include<bits/stdc++.h> using namespace std; const int maxn = 20 + 13; const int step[4][2] = {0,1,0,-1,1,0,-1,0}; bool Vis[maxn][maxn]; char Map[maxn][maxn]; int Num, N, M; void BFS(int x, int y) { Vis[x][y] = true; Num = 1; pair<int,int> Begin = make_pair(x, y); queue<pair<int,int> > Q; Q.push(Begin); while(!Q.empty()) { pair<int,int> tmp = Q.front(); Q.pop(); for(int i = 0; i < 4; ++i) { int xx = tmp.first + step[i][0]; int yy = tmp.second + step[i][1]; if(xx < 0 || xx >= N || yy < 0 || yy >= M || Vis[xx][yy]) continue ; if(Map[xx][yy] == ‘#‘) continue ; Num++; Vis[xx][yy] = true; Q.push(make_pair(xx, yy)); } } } int main() { int t; scanf("%d",&t); for(int kase = 1; kase <= t; ++kase) { scanf("%d %d",&M, &N); memset(Vis, 0, sizeof(Vis)); int x, y; for(int i = 0; i < N; ++i) { scanf("%s",Map[i]); for(int j = 0; j < M; ++j) { if(Map[i][j] == ‘@‘) { x = i, y = j; } } } BFS(x, y); printf("Case %d: %d\n",kase, Num); } }
原文:http://www.cnblogs.com/aoxuets/p/4915809.html