一开始你站在黑色的格子上, 每次可以上下左右走到相连的黑色格子, 但不能是红色格子, 求能走到的格子数
图的遍历, bfs和dfs都可以, 时间差不多
bfs
#include <cstdio>
int dx[] = {0, -1, 1, 0, 0};
int dy[] = {0, 0, 0, -1, 1};
char room[25][25], s[25];
bool vis[25][25];
int q[410];
int h, w;
void bfs(int x, int y)
{
int front, rear, u;
int count = 0;
front = rear = 1;
u = x*w+y;
q[rear++] = u;
count++;
while(front < rear)
{
x = (q[front]-1)/w;
y = (q[front++]-1)%w + 1;
for(int i=1; i<=4; i++)
{
int nx = x+dx[i];
int ny = y+dy[i];
if(room[nx][ny] == '.' && !vis[nx][ny])
{
vis[nx][ny] = 1;
q[rear++] = nx*w+ny;
count++;
}
}
}
printf("%d\n", count);
return;
}
int main()
{
while(scanf("%d %d", &w, &h), w, h)
{
int sx, sy;
for(int i=0; i<25; i++)
for(int j=0; j<25; j++)
{
room[i][j] = '#';
vis[i][j] = 0;
}
getchar();
for(int i=1; i<=h; i++)
{
scanf("%s", s);
for(int j=1; j<=w; j++)
room[i][j] = s[j-1];
}
for(int i=1; i<=h; i++)
for(int j=1; j<=w; j++)
if(room[i][j] == '@')
{
sx = i;
sy = j;
break;
}
bfs(sx, sy);
}
return 0;
}
dfs
#include <cstdio>
#include <cstring>
int dx[] = {0, -1, 1, 0, 0};
int dy[] = {0, 0, 0, -1, 1};
char room[25][25];
bool vis[25][25];
int sx, sy;
char s[25];
int count;
void dfs(int x, int y)
{
count++;
for(int i=1; i<=4; i++)
{
int nx = x+dx[i];
int ny = y+dy[i];
if(room[nx][ny] == '.' && !vis[nx][ny])
{
vis[nx][ny] = 1;
dfs(nx, ny);
//vis[nx][ny] = 0;
}
}
}
int main()
{
int w, h;
while(scanf("%d %d", &w, &h), w, h)
{
getchar();
for(int i=0; i<25; i++)
for(int j=0; j<25; j++)
room[i][j] = '#';
memset(vis, 0, sizeof(vis));
for(int i=1; i<=h; i++)
{
scanf("%s", s);
for(int j=1; j<=w; j++)
room[i][j] = s[j-1];
}
for(int i=1; i<=h; i++)
for(int j=1; j<=w; j++)
if(room[i][j] == '@')
{
sx = i;
sy = j;
break;
}
count = 0;
vis[sx][sy] = 1;
dfs(sx, sy);
printf("%d\n", count);
}
return 0;
}