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

 

 1 //DFS
 2 #include<iostream>
 3 int count,m,n;
 4 int dir[4][2]={-1,0,1,0,0,-1,0,1};
 5 char map[21][21];
 6 void DFS(int i,int j)
 7 {
 8     if(i<=0||i>m||j<=0||j>n)
 9         return;
10     for(int k=0;k<4;++k)
11         if(i+dir[k][0]>0&&i+dir[k][0]<=m&&j+dir[k][1]>0&&j+dir[k][1]<=n)
12             if(map[i+dir[k][0]][j+dir[k][1]]=='.')
13             {
14                 ++count;
15                 map[i+dir[k][0]][j+dir[k][1]]='#';
16                 DFS(i+dir[k][0],j+dir[k][1]);
17             }
18 }
19 int main()
20 {
21     using namespace std;
22     int i,j,stx,sty;
23     while(cin>>n>>m&&(n||m))
24     {
25         count=1;
26         for(i=1;i<=m;++i)
27             for(j=1;j<=n;++j)
28             {
29                 cin>>map[i][j];
30                 if(map[i][j]=='@')
31                 {
32                     stx=i;
33                     sty=j;
34                     map[i][j]='#';
35                 }
36             }
37         DFS(stx,sty);
38         cout<<count<<endl;
39     }
40     return 0;
41 }

 

 

 1 #include <iostream> 
 2 using namespace std;
 3 //宏定义增强代码适应能力和可读性
 4 #define MAX 22 
 5 char rect[MAX][MAX]; 
 6 
 7 int walkFrom(int currentRow, int currentCol); //返回从某点走过的格子数,减少全局量的使用
 8 void main()
 9 {
10     int col, row;
11     while(cin >> col >> row, col!=0 && row != 0)
12     { 
13         int i, j, startRow, startCol;
14         for(i = 0; i < MAX; i++)//intialize--方块四周加白色块,去掉边界判断,
15             for(j=0; j<MAX; j++)
16                 rect[i][j]='#'; 
17         for(i=1;i<=row;i++)
18             for(j=1;j<=col;j++)
19             {
20                 cin >> rect[i][j];
21                 if(rect[i][j] == '@')
22                 {
23                     startRow = i;
24                     startCol = j; 
25                     rect[i][j]='.';
26                 }
27             }
28         cout << walkFrom(startRow,startCol) << endl;
29     }
30 } 
31 int walkFrom(int currentRow, int currentCol)
32 { 
33       if(rect[currentRow][currentCol] == '#')
34               return 0; 
35       else
36           rect[currentRow][currentCol] = '#'; 
37       return  
38          1+walkFrom(currentRow+1,currentCol)+walkFrom(currentRow-1,currentCol)
39          +walkFrom(currentRow,currentCol+1)+walkFrom(currentRow,currentCol-1); 
40 } 

 

 

posted on 2012-06-21 17:14  可笑痴狂  阅读(242)  评论(0编辑  收藏  举报