题意 : 问一个m×n的矩形中,有多少个pocket,如果两块油田相连(上下左右或者对角连着也算),就算一个pocket 。
思路 : 写好8个方向搜就可以了,每次找的时候可以先把那个点直接变为*,这样可以避免重复搜索。
1 //POJ 1562 ZOJ 1709 2 3 #include <stdio.h> 4 #include <string.h> 5 #include <iostream> 6 #include <stack> 7 #include <algorithm> 8 9 using namespace std ; 10 11 char ch[110][110] ; 12 int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}} ; 13 int sum ; 14 int m,n ; 15 16 void DFS(int x,int y) 17 { 18 ch[x][y] = '*' ; 19 for(int i = 0 ; i < 8 ; i++) 20 { 21 int xx = x + dir[i][0] ; 22 int yy = y + dir[i][1] ; 23 if(xx >= 0 && xx <= m && yy >= 0 && yy <= n && ch[xx][yy] == '@') 24 { 25 DFS(xx,yy) ; 26 } 27 } 28 } 29 int main() 30 { 31 32 while(~scanf("%d %d",&m,&n)) 33 { 34 if(m == 0) break ; 35 for(int i = 0 ; i < m ; i++) 36 scanf("%s",ch[i]) ; 37 sum = 0 ; 38 for(int i = 0 ; i < m ; i++) 39 for(int j = 0 ; j < n ; j++) 40 { 41 if(ch[i][j] == '@') 42 { 43 DFS(i,j) ; 44 sum++ ; 45 } 46 } 47 printf("%d\n",sum) ; 48 } 49 return 0 ; 50 }