红与黑

铀是一道水题

有一个矩形房间,覆盖正方形瓷砖。每块瓷砖涂成了红色或黑色。一名男子站在黑色的瓷砖上,由此出发,可以移到四个相邻瓷砖之一,但他不能移动到红砖上,只能移动到黑砖上。编写一个程序,计算他通过重复上述移动所能经过的黑砖数(站立的黑砖也要算)。

输入

  开头行包含两个正整数W和H,W和H分别表示矩形房间的列数和行数,且都不超过20.
  每个数据集有H行,其中每行包含W个字符。每个字符的含义如下所示:
  '.'——黑砖
  '#'——红砖
  '@'——男子(仅出现一次)

输出

  男子从初始瓷砖出发可到达的瓷砖数

样例

样例输入1

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.

样例输出1

45

 

code:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 char mp[21][21];
 4 int w,h,vis[21][21],cnt;
 5 int a[4]={1,0,-1,0};
 6 int b[4]={0,1,0,-1}; 
 7 struct zb
 8 {
 9     int x,y;
10 }s;
11 queue<zb> q;
12 
13 void bfs()
14 {
15     zb now,nt;
16     q.push(s);
17     while(q.size())
18     {
19         now=q.front();
20         q.pop();
21         
22         for(int i=0;i<4;i++)
23         {
24             nt.x = now.x+a[i], nt.y = now.y+b[i];
25             if(!vis[nt.x][nt.y] && mp[nt.x][nt.y]=='.' && nt.x>=0 && nt.x<h && nt.y>=0 && nt.y<w)
26             {
27                 cnt++;
28                 vis[nt.x][nt.y]=1;
29                 q.push(nt);
30             }
31         } 
32     }
33 }
34 
35 int main()
36 {
37 
38     cin >> w >> h;
39     cnt=1;
40     for(int i=0;i<h;i++)
41     {
42         for(int j=0;j<w;j++)
43         {
44             cin >> mp[i][j];
45             if(mp[i][j]=='@')
46             {
47                 s.x=i;
48                 s.y=j;
49             }
50         }
51     }
52     bfs();
53     cout<<cnt;
54     return 0;
55 }

 

posted @ 2023-04-23 19:38  nasia  阅读(35)  评论(0)    收藏  举报