问题描述
有一个长方形的房间,覆盖着正方形的瓷砖。每个磁贴都被着色为红色或黑色。一个人站在黑色的瓷砖上。他可以从一个图块移动到四个相邻图块之一。但是他不能在红色瓷砖上移动,只能在黑色瓷砖上移动。
编写一个程序,通过重复上述动作来计算他可以到达的黑色瓷砖的数量。
本题既可以使用深度搜索也可以使用广度搜索
注意:
<1> 分清变量代表行还是列
wx是列 hy是行
bfs()函数中 dx是行 dy是列
Check()函数中 x是行 y是列
<2> 处理过的位置替换为‘#’ 避免重复处理
data[next.x][next.y]=’#’;
重复处理会导致运算量过大内存爆掉产生错误
terminate called after throwing an instance of ‘std::bad_alloc’
以下给出C++ 广度优先AC代码
#include<bits/stdc++.h>
using namespace std;
char data[21][21];
int num,wx,hy;
bool Check(int x,int y)
{
//x是行 y是列
//wx是列 hy是行
if(x<hy&&x>=0&&y<wx&&y>=0)
return true;
else
return false;
}
struct node
{
int x,y;
};
int dir[4][2]=
{
{-1,0},
{0,-1},
{1,0},
{0,1}
};
void bfs(int dx, int dy)
{
//x是行 y是列
num=1;
queue<node> q;
node start,next;
start.x=dx;
start.y=dy;
q.push(start);
while(!q.empty())
{
start=q.front();
q.pop();
for(int i=0; i<4; i++)
{
next.x=start.x+dir[i][0];
next.y=start.y+dir[i][1];
if(Check(next.x,next.y)&&(data[next.x][next.y]=='.'))
{
data[next.x][next.y]='#';
num++;
q.push(next);
}
}
}
return;
}
int main()
{
int x,y,dx,dy;
while(scanf("%d %d",&wx,&hy))
{
//wx是列 hy是行
getchar();
if (wx==0&&hy==0)
break;
for(y=0; y<hy; y++)
{
for(x=0; x<wx; x++)
{
scanf("%c",&data[y][x]);
if(data[y][x]=='@')
{
dy=y; //行
dx=x;//列
}
}
getchar();
}
bfs(dy,dx);
printf("%d\n",num);
}
return 0;
}
该博客介绍了如何用C++编写一个程序,解决一个人在只能在黑色瓷砖上移动的问题。通过广度优先搜索算法,计算出从初始位置可以到达的黑色瓷砖数量。程序中注意了坐标轴的处理,以及避免重复处理导致的错误。代码包括输入瓷砖布局,检查位置合法性,定义移动方向,以及进行广度优先搜索的函数。
416

被折叠的 条评论
为什么被折叠?



