虽然,虽然,这道题很简单。
但是我一直觉得我自己关于搜索可以算是一点都不会的,所以写得时候也是有点没底,可是,出乎意料的是我代码写完测了一下样例是对的,交了之后发现过了,还是很开心的!看题,想题,敲代码, 交题,AC!对,就是没有debug这一步,这种一顺溜,不用debug就过题的感觉真爽。第一次从搜索的题目上得到快感。
红与黑
Description
有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的黑色瓷砖移动。请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
Input
包括多个数据集合。每个数据集合的第一行是两个整数W和H,分别表示x方向和y方向瓷砖的数量。W和H都不超过20。在接下来的H行中,每行包括W个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.’:黑色的瓷砖;
2)‘#’:白色的瓷砖;
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
Output
对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。
Sample Input
Sample Output
45
【题目大意】见题面
【解法】明天再来补
【AC代码】
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <queue>
#define NMAX 23
using namespace std;
typedef struct Point{
int x;
int y;
};
char map[NMAX][NMAX];
int vis[NMAX][NMAX];
queue<Point>Q;
int ans;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int w, h;
bool check(int x, int y){
if(x >= 0 && x < h && y >= 0 && y < w){
return true;
}
return false;
}
int bfs(Point p){
Q.push(p);
ans++;
while(!Q.empty()){
Point temp = Q.front();
vis[temp.x][temp.y] = 1;
Q.pop();
for(int i = 0; i < 4; i++){
if(check(temp.x + dx[i], temp.y + dy[i]) && vis[temp.x + dx[i]][temp.y + dy[i]] == 0){
if(map[temp.x + dx[i]][temp.y + dy[i]] == '.'){
Point temp2;
temp2.x = temp.x + dx[i];
temp2.y = temp.y + dy[i];
Q.push(temp2);
ans++;
vis[temp.x + dx[i]][temp.y + dy[i]] = 1;
}
}
}
}
return ans;
}
int main(){
while(scanf("%d%d", &w, &h) != EOF && (w && h)){
memset(vis, 0, sizeof(vis));
ans = 0;
for(int i = 0; i < h; i++){
scanf("%s", &map[i]);
}
Point start;
for(int i = 0; i < h; i++){
for(int j = 0; j < w; j++){
if(map[i][j] == '@'){
start.x = i;
start.y = j;
}
}
}
printf("%d\n", bfs(start));
}
return 0;
}