HDU 1241 Oil Deposits
题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1241
最基本的图论问题
DFS 和BFS都能做
DFS
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define maxn 107 5 char map[maxn][maxn];//邻接矩阵存图 6 int visit[maxn][maxn];//标记节点是否被访问过0表示未被访问过1表示访问过 7 int dir[8][2] = {{0,1},{1,1},{-1,0},{0,-1},{1,0},{-1,-1},{1,-1},{-1,1}}; 8 //八个方向 9 int m,n; 10 void dfs(int x,int y) 11 { 12 int i; 13 for (i = 0; i < 8; ++i) 14 { 15 int tx = x + dir[i][0]; 16 int ty = y + dir[i][1]; 17 if (map[tx][ty] == '@' && tx >= 0 && tx < m && ty >= 0 && ty < n && !visit[tx][ty]) 18 { 19 visit[tx][ty] = 1; 20 dfs(tx,ty); 21 } 22 } 23 } 24 int main() 25 { 26 int i,j; 27 while (~scanf("%d%d",&m,&n)) 28 { 29 if (!m && !n) break; 30 int cnt = 0; 31 memset(visit,0,sizeof(visit)); 32 for (i = 0; i < m; ++i) scanf("%s",map[i]); 33 //邻接矩阵的O(n^2)找边 34 for (i = 0; i < m; ++i) 35 { 36 for (j = 0; j < n; ++j) 37 { 38 if (map[i][j] == '@' && !visit[i][j]) 39 { 40 visit[i][j] = 1; 41 cnt++; 42 dfs(i,j); 43 } 44 } 45 } 46 printf("%d\n",cnt); 47 } 48 return 0; 49 }
BFS
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define maxn 107 5 struct node 6 { 7 int x,y; 8 }; 9 char map[maxn][maxn];//邻接矩阵存图 10 int visit[maxn][maxn];//标记节点是否被访问过0表示未被访问过1表示访问过 11 int dir[8][2] = {{0,1},{1,1},{-1,0},{0,-1},{1,0},{-1,-1},{1,-1},{-1,1}}; 12 node q[maxn*maxn]; 13 //八个方向 14 int m,n,l,r; 15 void bfs() 16 { 17 int i; 18 while (l < r) 19 { 20 node pt = q[l++];//从队列中取出该节点 21 node p; 22 for (i = 0; i < 8; ++i)//寻找其八个方向 23 { 24 p.x = pt.x + dir[i][0]; 25 p.y = pt.y + dir[i][1]; 26 if (map[p.x][p.y] == '@' && p.x >= 0 && p.x < m 27 && p.y >= 0 && p.y < n && !visit[p.x][p.y])//满足条件 28 { 29 visit[p.x][p.y] = 1; 30 q[r++] = p;//入队列 31 } 32 } 33 } 34 } 35 36 int main() 37 { 38 //freopen("d.txt","r",stdin); 39 int i,j; 40 while (~scanf("%d%d",&m,&n)) 41 { 42 if (!m && !n) break; 43 int cnt = 0; 44 memset(visit,0,sizeof(visit)); 45 for (i = 0; i < m; ++i) scanf("%s",map[i]); 46 node p; 47 l = r =0; 48 for (i = 0; i < m; ++i) 49 { 50 for (j = 0; j < n; ++j) 51 { 52 if (map[i][j] == '@' && !visit[i][j]) 53 { 54 p.x = i; p.y = j; 55 q[r++] = p;//入队列 56 visit[i][j] = 1;//标记为已经访问过 57 cnt++; 58 bfs(); 59 } 60 } 61 } 62 printf("%d\n",cnt); 63 } 64 return 0; 65 }