您的位置:首页 > 其它

CodeForces 540C Ice Cave (BFS)

2016-07-25 11:25 501 查看
题意:给定 n * m的矩阵,让你并给定初始坐标和末坐标,你只能走'.',并且走过的'.'都会变成'X',然后问你能不能在末坐标是'X'的时候走进去。

析:这个题,在比赛时就是没做出来,其实是一个水题,但是我理解错了意思,让下面提示的第一组样例给搞乱。

思路应该是这样的,从开始坐标BFS末坐标,把经过的都标成'X',如果直到末坐标是'.',接着走,如果能直到末坐标是'X',就是可以,否则就是不可以。

代码如下:

#include <bits/stdc++.h>

using namespace std;
typedef long long LL;
const int maxn = 500 + 5;
const int INF = 0x3f3f3f3f;
const int dr[] = {0, 0, 1, -1};
const int dc[] = {1, -1, 0, 0};
struct node{
int r, c;
node(int rr = 0, int cc = 0) : r(rr), c(cc) { }
};
int n, m;
char s[maxn][maxn];
int r2, c2;

bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}

bool bfs(int r, int c){
queue<node> q;
q.push(node(r, c));
s[r][c] = 'X';
while(!q.empty()){
node u = q.front();  q.pop();
for(int i = 0; i < 4; ++i){
int x = u.r + dr[i];
int y = u.c + dc[i];
if(x == r2 && y == c2 && s[x][y] == 'X')  return true;
if(is_in(x, y) && s[x][y] == '.'){
s[x][y] = 'X';
q.push(node(x, y));
}
}
}
return false;
}

int main(){
scanf("%d %d", &n, &m);
for(int i = 0; i < n; ++i)
scanf("%s", s[i]);
int r1, c1;
cin >> r1 >> c1 >> r2 >> c2;
--r1, --r2, --c1, --c2;
if(bfs(r1, c1))  puts("YES");
else  puts("NO");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: