HDU 1241 Oil Deposits(经典DFS)
作者:互联网
嗯...
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1241
很经典的一道dfs,但是注意每次查到一个@之后,都要把它变成“ * ”,然后继续dfs,这样在dfs过程中一些@变成了“ * ”。这样也不需要flag数组,当继续遍历图的时候,再有@就是独立的,ans++。最后ans里边便是答案...
AC代码:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 5 using namespace std; 6 7 int n, m, ans; 8 int dir[8][2] = {{-1, 0}, {-1, -1}, {-1, 1}, {0, 1}, {0, -1}, {1, 1}, {1, 0}, {1, -1}}; 9 char g[105][105]; 10 11 inline void dfs(int x, int y){ 12 for(int i = 0; i < 8; i++){ 13 int nx = x + dir[i][0]; 14 int ny = y + dir[i][1]; 15 if(nx > 0 && ny > 0 && nx <= n && ny <= m && g[nx][ny] == '@'){ 16 g[x][y] = '*'; 17 g[nx][ny] = '*'; 18 dfs(nx, ny); 19 } 20 } 21 } 22 23 int main(){ 24 while(~scanf("%d%d", &n, &m) && n + m != 0){ 25 ans = 0; 26 for(int i = 1; i <= n; i++){ 27 for(int j = 1; j <= m; j++){ 28 cin >> g[i][j]; 29 } 30 } 31 for(int i = 1; i <= n; i++){ 32 for(int j = 1; j <= m; j++){ 33 if(g[i][j] == '@'){ 34 ans++; 35 dfs(i, j); 36 } 37 } 38 } 39 printf("%d\n", ans); 40 } 41 return 0; 42 }AC代码
标签:HDU,Oil,int,Deposits,dfs,nx,ans,include,dir 来源: https://www.cnblogs.com/New-ljx/p/11436902.html