解题思路:
1. 遍历扫描二维数组,遇到‘@’,结果ans++;
2. 将当前 i,j 位置置为‘*’,将当前‘@’的 i,j 传人到DFS函数中,开始遍历八个方向的字符
如果碰到 '@' 则先将当前置为‘*’,然后再次递归传递,直到超出界限或者扫描不到‘@’,结束递归
3. DFS()的作用是将i,j为开始周围连续的“@”全部改为‘*’
4. 最后输出 ans 即可;
Ac code :
1 #include<bits/stdc++.h> 2 using namespace std; 3 char xstr[104][104]; 4 static int ans; 5 int x,y; 6 void dfs(int i,int j) 7 { 8 9 if(j+1<y&&xstr[i][j+1]=='@') 10 { 11 xstr[i][j+1]='*'; 12 dfs(i,j+1); 13 } 14 if(i+1<x&&j-1>=0&&xstr[i+1][j-1]=='@') 15 { 16 xstr[i+1][j-1]='*'; 17 dfs(i+1,j-1); 18 } 19 if(i+1<x&&xstr[i+1][j]=='@') 20 { 21 xstr[i+1][j]='*'; 22 dfs(i+1,j); 23 } 24 if(i+1<x&&j+1<y&&xstr[i+1][j+1]=='@') 25 { 26 xstr[i+1][j+1]='*'; 27 dfs(i+1,j+1); 28 } 29 if(i-1>=0&&j+1<y&&xstr[i-1][j+1]=='@') 30 { 31 xstr[i-1][j+1]='*'; 32 dfs(i-1,j+1); 33 } 34 if(j-1>=0&&xstr[i][j-1]=='@') 35 { 36 xstr[i][j-1]='*'; 37 dfs(i,j-1); 38 } 39 if(i-1>=0&&xstr[i-1][j]=='@') 40 { 41 xstr[i-1][j]='*'; 42 dfs(i-1,j); 43 } 44 if(i-1>=0&&j-1>=0&&xstr[i-1][j-1]=='@') 45 { 46 xstr[i-1][j-1]='*'; 47 dfs(i-1,j-1); 48 } 49 } 50 int main() 51 { 52 53 while(scanf("%d%d",&x,&y)!=EOF&&x+y) 54 { 55 ans=0; 56 memset(xstr,0,sizeof(xstr)); 57 int i,j; 58 for(i=0; i<x; i++) 59 { 60 scanf("%s",&xstr[i]); 61 } 62 for(i=0; i<x; i++) 63 { 64 for(j=0; j<y; j++) 65 { 66 if(xstr[i][j]=='@') 67 { 68 xstr[i][j]='*'; 69 ans++; 70 dfs(i,j); 71 } 72 } 73 } 74 printf("%d ",ans); 75 } 76 return 0; 77 }