题目链接:AcWing 1113. 红与黑
有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。
你站在其中一块黑色的瓷砖上,只能向相邻(上下左右四个方向)的黑色瓷砖移动。
请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
输入格式
输入包括多个数据集合。
每个数据集合的第一行是两个整数 W 和 H,分别表示 x 方向和 y 方向瓷砖的数量。
在接下来的 H 行中,每行包括 W 个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.
’:黑色的瓷砖;
2)‘#
’:红色的瓷砖;
3)‘@
’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
输出格式
对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。
数据范围
1≤W,H≤20
输入样例:
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
0 0
输出样例:
45
宽搜(bfs)写法:
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
#define x first
#define y second
const int maxn = 25;
char g[maxn][maxn];
int w, h; //w列数 h行数
int x, y; //起点的坐标
int bfs(int sx, int sy){
queue<pair<int, int>> q;
q.push({sx, sy}); //起点入队
g[sx][sy] = '#' ;
int res = 0;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
while(q.size()){
auto t = q.front();
q.pop();
res++;
for(int i = 0; i < 4; i ++ ){
int x = t.x + dx[i], y = t.y + dy[i];
if(x < 0 || x >= h || y < 0 || y >= w || g[x][y] != '.') continue; //不满足就continue
g[x][y] = '#';
q.push({x, y});
}
}
return res;
}
int main(){
while(cin >> w >> h, w || h){ //只要输入的不是0 0
for(int i = 0; i < h; i ++ ) cin >> g[i]; //一次读入一行
for(int i = 0; i < h; i ++ ){
for(int j = 0; j < w; j ++ ){
if(g[i][j] == '@'){
x = i;
y = j;
}
}
}
cout << bfs(x, y) << endl;
}
return 0;
}
深搜(dfs)写法:
#include <iostream>
using namespace std;
const int maxn = 25;
char g[maxn][maxn];
int w, h; //w列数 h行数
int x, y; //起点的坐标
int dfs(int x, int y){
g[x][y] = '#';
int ans = 1;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
for(int i = 0; i < 4; i ++ ){
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < h && b >= 0 && b < w && g[a][b] == '.')
ans += dfs(a, b);
}
return ans;
}
int main(){
while(cin >> w >> h, w || h){ //只要输入的不是0 0
for(int i = 0; i < h; i ++ ) cin >> g[i]; //一次读入一行
for(int i = 0; i < h; i ++ ){
for(int j = 0; j < w; j ++ ){
if(g[i][j] == '@'){
x = i;
y = j;
}
}
}
cout << dfs(x, y) << endl;
}
return 0;
}
python写法:
def bfs(x, y, n, m):
queue = [(x, y)]
hh, tt = 0, 0
cnt = 1
move = [(0, 1), (1, 0), (-1, 0), (0, -1)]
while hh <= tt:
sx, sy = queue[hh]
hh += 1
for i, j in move:
nx, ny = sx + i, sy + j
if 0 <= nx < n and 0 <= ny < m and grids[nx][ny] == '.':
queue.append((nx, ny))
tt += 1
cnt += 1
grids[nx][ny] = '-'
return cnt
while True:
# map第一个参数接受一个函数名,后面的参数接受一个或多个可迭代的序列,返回的是一个集合
m, n = map(int, input().split())
if m == 0 and n == 0: break
grids = []
for _ in range(n):
grids.append(list(input()))
for i in range(n):
for j in range(m):
if grids[i][j] == '@':
x, y = i, j
break
res = bfs(x, y, n, m)
print(res)