HDOJ 1241 Oil Deposits【最大连通块 dfs】

HDOJ 1241 Oil Deposits【最大连通块 dfs】

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1241


输入那里很烦。。。


 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cstring>
 5 using namespace std;
 6 const int MAXL = 105; // 矩阵最大宽度
 7 char maze[MAXL][MAXL]; // 迷宫
 8 int vis[MAXL][MAXL]; // 访问标记(坐标点所在连通块编号)
 9 int n, m; // 迷宫的长和宽
10 int dirx[8] = {0, 1, 0, -1, 1, 1, -1, -1};
11 int diry[8] = {1, 0, -1, 0, 1, -1, -1, 1}; // 移动方向
12 typedef struct point{
13     int x, y;
14 }P; // 坐标
15 
16 void Output(){
17     for(int i = 0; i < n; i++){
18         for(int j = 0; j < m; j++){
19             printf("%c", maze[i][j]);
20         }
21         printf("
");
22     }
23 }
24 
25 void Input(){
26     memset(maze, 0, sizeof(maze));
27     memset(vis, 0, sizeof(vis));
28     for(int i = 0; i < n; i++){
29             scanf("%s", &maze[i]);
30         }
31     //Output();
32 }
33 
34 void dfs(int x, int y, int cnt){
35     if(x < 0 || x >= n || y < 0 || y >= m) return; // 越界 返回
36     if(maze[x][y] == '*' || vis[x][y] != 0) return; // 没有油或已经访问过 返回
37     vis[x][y] = cnt;
38     for(int i = 0; i < 8; i++){
39         dfs(x+dirx[i], y+diry[i], cnt); // 遍历邻接点
40     }
41 }
42 
43 int Sum(){
44     int cnt = 0; // 连通块的数量
45     for(int i = 0; i < n; i++){
46         for(int j = 0; j < m; j++){
47             if(maze[i][j] == '@' && vis[i][j] == 0){ // 有油并且没有标记过
48                 dfs(i, j, ++cnt);
49             }
50         }
51     }
52     return cnt;
53 }
54 
55 int main(){
56     while(~scanf("%d%d", &n, &m) && n && m){
57         Input();
58         printf("%d
", Sum());
59     }
60 
61     return 0;
62 }
原文地址:https://www.cnblogs.com/miaowTracy/p/4836774.html