hdu 1241 Oil Deposits_dfs or bfs
题意:给你n*m的图,@代表有油田的格子,*代表没油田的格子,如果油田旁边有油田就合并一起成为一个油田区,合并的方向为8个,现在问你油田合并过后,有多少个油田区
解法:用dfs or bfs
dfs:
#include<iostream> using namespace std; char map[102][102]; int dir[8][2]={{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}}; void dfs(int x,int y) { int i,x1,y1; if(map[x][y]=='@') { map[x][y]='*'; for(i=0;i<8;i++) { x1=x+dir[i][0]; y1=y+dir[i][1]; dfs(x1,y1); } } } int main() { int n,m,i,j,ans; while(cin>>n>>m,n||m) { ans=0; for(i=0;i<n;i++) for(j=0;j<m;j++) cin>>map[i][j]; getchar(); for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(map[i][j]=='@') { dfs(i,j); ans++; } } } cout<<ans<<endl; } return 0; }
#include<iostream> #include<queue> using namespace std; int dir[8][2]={{1,0},{0,1},{-1,0},{0,-1},{1,-1},{-1,1},{-1,-1},{1,1}}; char map[102][102]; int n,m,ans; struct node { int x; int y; }begin,end; int bfs() { queue<node>q; node temp,t; int i,ans=0; q.push(begin); while(!q.empty()) { t=q.front(); q.pop(); for(i=0;i<8;i++) { temp.x=t.x+dir[i][0]; temp.y=t.y+dir[i][1]; if(map[temp.x][temp.y]!='*'&&temp.x>=0&&temp.x<n&&temp.y>=0&&temp.y<m) { q.push(temp); map[temp.x][temp.y]='*'; } } } return 0; } int main() { int i,j; while(cin>>n>>m,n||m) { ans=0; for(i=0;i<n;i++) { getchar(); for(j=0;j<m;j++) { cin>>map[i][j]; } } for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(map[i][j]=='@') { begin.x=i; begin.y=j; map[i][j]='*'; bfs(); ans++; } } } cout<<ans<<endl; } return 0; }
不怕路长,只怕心老.