ZOJ-2165* 迷宫问题

2165:给出初始位置,给出不可走区域,求能够到达的位置个数。

Sample Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0


Sample Output

45
59
6
13


思路:DFS遍历。上下左右按一定顺序递归,全局变量进行统计。
注意二维数组的第一个下标对应高度值,第二个下标对应宽度值。

#include<iostream>
using namespace std;
#include<memory.h>
#include<stdio.h>

int map[21][21];
int sum;
int ori[4][2]={
0,1,//right
0,-1,//left
1,0,//up
-1,0 //down
};

bool legal(int x,int y,int w,int h)
{
if(x>=h||x<0)
return false;
if(y>=w||y<0)
return false;
else
return true;
}

void DFS(int x,int y,int w,int h)
{
int tx,ty,i;
sum++;
map[x][y]=1; // no more visit

for(i=0;i<4;i++)
{
tx=x+ori[i][0];
ty=y+ori[i][1];
if(!map[tx][ty]&&legal(tx,ty,w,h))
{
DFS(tx,ty,w,h);
}
}
}


int main()
{
int W;
int H;
int x;
int y;
char c;

while(1)
{
scanf("%d%d",&W,&H);

if((W||H)==0) //= is higher than or
break;

memset(map,0,sizeof(map));
for(int i=0;i<H;i++)
{
getchar();
for(int j=0;j<W;j++)
{
c=getchar();
if(c=='#')
{
map[i][j]=1;
}
else if(c=='@')
{
x=i;
y=j;
}
}
}

sum=0;
DFS(x,y,W,H);
printf("%d\n",sum);


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值