您的位置:首页 > 其它

Robort In Maze问题

2015-11-25 16:04 351 查看

Robort in maze问题

自从用Evernote来学习,记笔记,blog上好久没有学习痕迹了。废话少说,来看题目吧!这是一个广搜(Breadth Fisrst Search)比较基础的题。

Q:有一个矩形的房间,覆盖着广场砖,瓷砖颜色有红,黑两种。一个人站在一个黑色的瓷砖上,他可以从现在站的瓷砖搬到四个相邻的瓷砖,即上,下,左,右。规则是,他不能再红色瓷砖上移动,他只能在黑色瓷砖上移动。

编写程序统计黑色瓷砖的块儿数,他可以达到通过重复上述动作。

input:包含多组测试实例,包含两个数据w,h;w和h是瓷砖的数量在x,-y方向的行和列数,(0< w,h<=20),定义如下:

“.”一个黑色的瓷砖

“#”一个红色的瓷砖

“@”一个机器人在一个黑色瓷砖上(一个测试数据仅出现一个)

output:对于每个数据集,你的程序应该输出一行,包含了黑色瓷砖的数量可以到达从最初的瓷砖(包括自己)

测试用例:

6 9

….#.

…..#

……

……

……

……

……

#@…#

.#..#.

11 9

.#………

.#.#######.

.#.#…..#.

.#.#.###.#.

.#.#..@#.#.

.#.#####.#.

.#…….#.

.##########

………..

Sample Output:

45

59

C++实现源代码:

#include< stdio.h>

#include< stdio.h>

#include< string.h>

#include< iostream>

#include< queue>

#include< algorithm>

using namespace std;

struct node{

int node_x;

int node_y;

};

node cur,dfs; //dfs为下一个要搜索的点

const int MAX_SIZE=100;

char map[MAX_SIZE][MAX_SIZE];
int mark[MAX_SIZE][MAX_SIZE];
queue<node> q;
node  direction[4];
int main(){
int num_row,num_col;
int count_step=0,flag1=0,flag2=0;
direction[0].node_x=-1; //上
direction[0].node_y=0;
direction[1].node_x=1;  //下
direction[1].node_y=0;
direction[2].node_x=0;  //左
direction[2].node_y=-1;
direction[3].node_x=0;  //右
direction[3].node_y=1;
while(scanf("%d%d",&num_col,&num_row)!=EOF){
if(num_row==0||num_col==0)
break;
getchar();
count_step=0;
memset(mark,0,sizeof(mark));
for(int i=0;i<num_row;i++){ //initialize the map array
for(int j=0;j<num_col;j++){
scanf("%c",&map[i][j]);
if(map[i][j]=='@'){
flag1=i;
flag2=j;
count_step=1;
mark[i][j]=1;
}
}
getchar();
}
while(!q.empty()){
q.pop();
}
cur.node_x=flag1;
cur.node_y=flag2;
q.push(cur);
while(!q.empty()){
cur=q.front();
q.pop();
dfs.node_x=cur.node_x+direction[i].node_x;            dfs.node_y=cur.node_y+direction[i].node_y;
if(dfs.node_x<0||dfs.node_x>num_row||dfs.node_y<0||dfs.node_y>num_col){   //搜索越界
continue;
}
if(map[dfs.node_x][dfs.node_y]=='#'){
//do nothing
continue;
}
if(mark[dfs.node_x][dfs.node_y]==1){
continue;
}
if(map[dfs.node_x][dfs.node_y]=='.'&&mark[dfs.node_x][dfs.node_y]==0){
mark[dfs.node_x][dfs.node_y]=1;
count_step+=1;
q.push(dfs);
}

}
}
printf("%d",count_step);
}
return 0;
}


ps:该题是一个很典型的bfs的练习题,注意测试实例给的是先输入的是col,后输入的是row,不然test输出会有问题,我就在这儿等了好久才看出来。

文章原创,转载请标明出处Robort In Maze/article/10306916.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: