测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A26683. 红与黑

填空题 困难

题目描述

红与黑

题目描述

有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的黑色瓷砖移动。请写一个程序,计算你总共能够到达多少块黑色的瓷砖。

输入

包括多组数据。每组数据的第一行是两个整数W和H,分别表示x方向和y方向瓷砖的数量。W和H都不超过20。在接下来的H行中,每行包括W个字符。每个字符表示一块瓷砖的颜色,规则如下:

1)‘.’:黑色的瓷砖;

2)‘#’:红色的瓷砖;

3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每组数据中唯一出现一次。

当在一行中读入的是两个零时,表示输入结束。

输出

对每组数据,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。

输入样例

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

输出样例

45

参考答案

#include <bits/stdc++.h> using namespace std; #define N 25 char mp[N][N];//地图 int w, h, ct;//h:行数,w:ct:结果计数 int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//方向数组 bool vis[N][N]; void dfs(int sx, int sy) { for(int i = 0; i < 4; ++i) { int x = sx + dir[i][0], y = sy + dir[i][1]; if(x >= 1 && x <= h && y >= 1 && y <= w && vis[x][y] == false && mp[x][y] != '#') { ct++; vis[x][y] = true; dfs(x, y); } } } int main() { int stx, sty;//起始位置 while(true) { cin >> w >> h; if(w == 0 && h == 0) return 0; for(int i = 1; i <= h; ++i) for(int j = 1; j <= w; ++j) { cin >> mp[i][j]; if(mp[i][j] == '@') stx = i, sty = j; } memset(vis, 0, sizeof(vis));//多组数据,注意状态还原 ct = 1; vis[stx][sty] = true; dfs(stx, sty); cout << ct << endl; } return 0; }

答案解析

#include <bits/stdc++.h>

using namespace std;

#define N 25

struct Node

{

int x, y;

Node(){}

Node(int a, int b):x(a),y(b){}

};

char mp[N][N];//地图

int w, h;//w:列数 h:行数

int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//方向数组

bool vis[N][N];

int bfs(int sx, int sy)//传入起始位置

{

queue<Node> que;

vis[sx][sy] = true;

que.push(Node(sx, sy));

int ct = 1;//计数,看可以到达几个黑色格子

while(que.empty() == false)

{

Node u = que.front();

que.pop();

for(int i = 0; i < 4; ++i)

{

int x = u.x + dir[i][0], y = u.y + dir[i][1];

if(x >= 1 && x <= h && y >= 1 && y <= w && vis[x][y] == false && mp[x][y] != '#')

{

vis[x][y] = true;

que.push(Node(x, y));

ct++;

}

}

}

return ct;

}

int main()

{

int stx, sty;

   while(true)

   {

    cin >> w >> h;

if(w == 0 && h == 0)

    return 0;

    for(int i = 1; i <= h; ++i)

    for(int j = 1; j <= w; ++j)

    {

    cin >> mp[i][j];

    if(mp[i][j] == '@')

    stx = i, sty = j;

    }

    memset(vis, 0, sizeof(vis));

    cout << bfs(stx, sty) << endl;

}

   return 0;

}


上一题 下一题