油田(DFS)
//DFS:油田问题 #include <iostream> using namespace std; char grid[101][101]; int n,m; //一个网格的8个方向 int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; //从(x,y)进行深度优先遍历 void DFS(int x,int y) { int xx,yy; grid [x][y] = '*'; for (int i = 0; i < 8; i++) { xx = x + dir[i][0]; yy = y + dir[i][1]; if(xx<0 || xx>=n || yy<0 ||yy>=m) continue; if(grid[xx][yy] =='@') DFS(xx,yy); } } int main() { int i,j;//定义循环变量 int count; while(cin>>n>>m) { if(n==0 && m ==0) break; count = 0; memset(grid,0,sizeof(grid)); for(i = 0; i<n; i++) cin>>grid[i]; for(i = 0; i<n; i++) for(j = 0; j<m;j++) if(grid[i][j]=='@') { //在(i,j)遍历,并且遍历了一个“油田”,计数器加1 DFS(i,j); count++; } cout<<count<<endl; } return 0; }