简单搜索——杭电1312Red and Black

Red and Black

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20144    Accepted Submission(s): 12243


Problem Description
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.

Write a program to count the number of black tiles which he can reach by repeating the moves described above.
 

 

Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.

There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.

'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
 

 

Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
 

 

Sample Input
简单搜索——杭电1312Red and Black_第1张图片

 

Sample Output
45
59
6
13
代码实现
 1 #include
 2 char map[22][22];
 3 int que[1000][2];
 4 int sx[4]={0,0,-1,1};
 5 int sy[4]={1,-1,0,0};
 6 int h,w;
 7 int dfs(int x,int y)
 8 {
 9     int t,xx,yy,i,j,s=1;
10     i=j=0;
11     que[i][0]=x;
12     que[i][1]=y;
13     i++;
14     map[x][y]='#';
15     while(j<i)
16     {
17         xx=que[j][0];
18         yy=que[j][1];
19         for(t=0;t<4;t++)
20         {
21             x=xx+sx[t];
22             y=yy+sy[t];
23             if(x>=1&&x<=h&&y>=1&&y<=w&&map[x][y]!='#')
24             {
25                 que[i][0]=x;
26                 que[i][1]=y;
27                 i++;
28                 map[x][y]='#';
29                 s++;
30             }
31         }
32         j++;
33     }
34     return s;
35 }
36 
37 int main()
38 {
39     int i,j,x,y;
40     while(scanf("%d%d",&w,&h)!=EOF)
41     {
42         if(h==0&&w==0)break;
43         for(i=1;i<=h;i++)
44         {
45             getchar();
46             for(j=1;j<=w;j++)
47             {
48                 scanf("%c",&map[i][j]);
49                 if(map[i][j]=='@')
50                 {
51                     x=i;
52                     y=j;
53                 }
54             }
55         }
56         printf("%d\n",dfs(x,y));
57     }
58     return 0;
59 }

 

你可能感兴趣的:(简单搜索——杭电1312Red and Black)