题意:n*m的地图,'X'表示有裂痕的冰块,'.'表示完整的冰块,
有裂痕的冰块再被踩一次就会碎掉,完整的冰块被踩一次会变成有裂痕的冰块,
现在告诉起点和终点,问从起点能否走到终点并且使终点的冰块碎掉。不能原地跳。
起点和终点可能会在同一个位置。
思路1:bfs。从起点开始广搜,起点默认为X。
若碰到X,判断是否为终点。若是,结束算法,否则无法行走。
若碰到.,则变为X。
#include <cstdio>
#include <algorithm>
#include <queue>
#define N 505
using namespace std;
int n, m;
char map[N][N];
int sx, sy, ex, ey;
typedef struct note {
int x; int y;
}point;
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
int isok(int x, int y)
{
return x >= 0 && x < n && y >= 0 && y < m;
}
int bfs()
{
queue<point> q;
while (q.size()) q.pop();
//初始化起点
point s;
s.x = sx; s.y = sy;
q.push(s);
map[s.x][s.y] = 'X';
while (q.size())
{
point cur = q.front(); q.pop();//出队
point t;
for (int i = 0; i < 4; i++)//遍历4个方向
{
t.x = cur.x + dx[i]; t.y = cur.y + dy[i];
if (!isok(t.x, t.y))//越界
continue;
if (map[t.x][t.y] == 'X')//到达X
{
if (t.x == ex && t.y == ey)//到达终点
return 1;
else//不可达
continue;
}
if (map[t.x][t.y] == '.')//到达.
{
q.push(t);
map[t.x][t.y] = 'X';
}
}
}
return 0;
}
int main()
{
while (~scanf("%d%d", &n, &m))
{
for (int i = 0; i < n; i++)
scanf("%s", map[i]);
scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
sx--; sy--; ex--; ey--;
if (bfs())
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
思路2:dfs。dfs一般用于判断是否能到达。此题正好适合,不过dfs在用于判断是否到达的问题时,
标记数组退栈时不用消除。(原因:若当前点不能到达,下次更不用搜索该点了)
#include <cstdio>
#include <algorithm>
#define N 505
using namespace std;
int n, m;
char map[N][N];
int sx, sy, ex, ey;
int flag = 0;
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
int isok(int x, int y)
{
return x >= 0 && x < n && y >= 0 && y < m;
}
void dfs(int x, int y)
{
for (int i = 0; i < 4; i++)
{
int tx = x + dx[i], ty = y + dy[i];
if (!isok(tx, ty))
continue;
//对当前点分为终点和非终点两种情况
if (tx == ex && ty == ey)
{
if (map[tx][ty] == 'X')
{
flag = 1;
return;
}
else//终点是.
{
map[tx][ty] = 'X';
dfs(tx, ty);
}
}
else//非终点
{
if (map[tx][ty] == 'X')
continue;
else//是.
{
map[tx][ty] = 'X';
dfs(tx, ty);
}
}
}
}
int main()
{
while (~scanf("%d%d", &n, &m))
{
for (int i = 0; i < n; i++)
scanf("%s", map[i]);
scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
sx--; sy--; ex--; ey--;
map[sx][sy] = 'X';
dfs(sx, sy);
if (flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}