题意:
一个有障碍物的地图,给定起点,问有多少个地图中的方块是可以走到的?
类似于地图问题,由于只要求能达到的方块数,不涉及第几步走到哪里这些信息。
所以可以使用队列帮助的BFS,走到的地方标记之,计数器++,当队列为空时,搜索结束,计数器即为结果。
使用了迷宫问题的几个典型处理手段:
1)外围加一圈围墙,将边界一般化;
2)使用一个位移数组,帮助搜索。
代码如下:
using namespace std;
struct position
{
int x;
int y;
};
int main()
{
int W,H;
while (true)
{
cin>>W>>H;
if(W==0&&H==0)
break;
int grids[22][22] = {0};
//围墙,消除边界差异性
for (int i = 0;i <= W+1;i++)
{
grids[0][i] = 1; //顶
grids[H+1][i] = 1; //底
}
for (int i = 0;i <= H+1;i++)
{
grids[i][0] = 1; //左边
grids[i][W+1] = 1; //右边
}
//位移数组
position offset[4];
offset[0].x = 1;
offset[0].y = 0;
offset[1].x = 0;
offset[1].y = 1;
offset[2].x = -1;
offset[2].y = 0;
offset[3].x = 0;
offset[3].y = -1;
char ch;
position start;
for (int i = 1; i <= H;i++)
{
for (int j = 1; j<= W;j++)
{
cin>>ch;
if (ch == '.')
{
grids[i][j] = 0;
}
else if (ch == '#')
{
grids[i][j] = 1;
}
else if (ch == '@')
{
start.x = j;
start.y = i;
grids[i][j] = 1;
}
}
}
queue<position> q;
int count = 1;
q.push(start);
position here,next;
while (!q.empty())
{
here = q.front();
q.pop();
for (int i = 0;i <= 3;i++)
{
next.x = here.x + offset[i].x;
next.y = here.y + offset[i].y;
if (grids[next.y][next.x] == 0)
{
q.push(next);
grids[next.y][next.x] = 1;
count++;
}
}
}
cout<<count<<endl;
}
}