#301 (div.2) C. Ice Cave
來源:程序員人生 發布時間:2015-06-05 09:35:10 閱讀次數:3624次
1.題目描寫:點擊打開鏈接
2.解題思路:本題利用BFS解決。由于行走的時候有兩種情況,當遇到‘X'時會掉到下1層,當遇到’.'時還在本層,只不過’.'要變成'X'。那末直接用BFS進行搜索便可。如果遇到了’X',只需要判斷是否是終點便可,否則跳過,如果遇到了‘.',那末將它改成‘X',并入隊列便可。比賽時我1直在DFS和BFS之間徘徊不定,但其實不難發現,如果用DFS的話,可能有走不動的情況,需要往回撤。時間復雜度會比較高,因此自然會想到BFS。
3.代碼:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;
#define N 500+5
int n, m;
int s, t, e, d;
int dx[] = { 1, ⑴, 0, 0 };
int dy[] = { 0, 0, 1, ⑴ };
char g[N][N];
typedef pair<int, int>P;
bool bfs()
{
queue<P>q;
q.push(P(s,t));
g[s][t] = 'X';
while (!q.empty())
{
s = q.front().first, t = q.front().second; q.pop();
for (int i = 0; i < 4; i++)
{
int xx = s + dx[i];
int yy = t + dy[i];
if (xx < 0 || xx >= n || yy < 0 || yy >= m)continue;
if (g[xx][yy] == 'X')
{
if (xx == e&&yy == d)return true;
continue;
}
g[xx][yy] = 'X';
q.push(P(xx, yy));
}
}
return false;
}
int main()
{
//freopen("t.txt", "r", stdin);
while (~scanf("%d%d", &n, &m))
{
for (int i = 0; i < n; i++)
scanf("%s", g[i]);
scanf("%d%d%d%d", &s, &t, &e, &d);
s--, t--, e--, d--;
printf("%s
", bfs() ? "YES" : "NO");
}
return 0;
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈