C语言编程练习58:红与黑
题目描述
小明站在一个矩形房间里,这个房间的地面铺满了地砖,每块地砖的颜色或是红色或是黑色。小明一开始站在一块黑色地砖上,并且小明从一块地砖可以向上下左右四个方向移动到其他的地砖上,但是他不能移动到红色地砖上,只能移动到黑色地砖上。
请你编程计算小明可以走到的黑色地砖最多有多少块。
请你编程计算小明可以走到的黑色地砖最多有多少块。
输入
输入包含多组测试数据。
每组输入首先是两个正整数W和H,分别表示地砖的列行数。(1<=W,H<=20)
接下来H行,每行包含W个字符,字符含义如下:
‘.’表示黑地砖;
‘#’表示红地砖;
‘@’表示小明一开始站的位置,此位置是一块黑地砖,并且这个字符在每组输入中仅会出现一个。
当W=0,H=0时,输入结束。
每组输入首先是两个正整数W和H,分别表示地砖的列行数。(1<=W,H<=20)
接下来H行,每行包含W个字符,字符含义如下:
‘.’表示黑地砖;
‘#’表示红地砖;
‘@’表示小明一开始站的位置,此位置是一块黑地砖,并且这个字符在每组输入中仅会出现一个。
当W=0,H=0时,输入结束。
输出
对于每组输入,输出小明可以走到的黑色地砖最多有多少块,包括小明最开始站的那块黑色地砖。
样例输入 Copy
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
样例输出 Copy
45
59
6
13
思路:dfs
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
using namespace std;
int c[4][2]={{0,-1},{0,1},{-1,0},{1,0}};//下一步的4种选择
int w,h,ans;
int x,y;
char s[22][22];
void dfs(int a,int b)
{
ans++;
s[a][b]='@';
int n,m;
for(int i=0;i<4;i++)
{
n=a+c[i][0];
m=b+c[i][1];
if(n<h&&m<w&&n>=0&&m>=0&&s[n][m]=='.')
{
dfs(n,m);
}
}
}
int main()
{
while(cin>>w>>h&&(w!=0)&&(h!=0))
{
ans=0;
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
cin>>s[i][j];
if(s[i][j]=='@')
{
x=i;
y=j;
}
}
}
dfs(x,y);
printf("%d\n",ans);
}
return 0;
}

浙公网安备 33010602011771号