#301 (div.2) C. Ice Cave

來源:互聯網
上載者:User

標籤:bfs

1.題目描述:點擊開啟連結

2.解題思路:本題利用BFS解決。由於行走的時候有兩種情況,當遇到‘X‘時會掉到下一層,當遇到’.‘時還在本層,只不過’.‘要變為‘X‘。那麼直接用BFS進行搜尋即可。如果遇到了’X‘,只需要判斷是不是終點即可,否則跳過,如果遇到了‘.‘,那麼將它改為‘X‘,併入隊列即可。比賽時我一直在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+5int n, m;int s, t, e, d;int dx[] = { 1, -1, 0, 0 };int dy[] = { 0, 0, 1, -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\n", bfs() ? "YES" : "NO");}return 0;}

#301 (div.2) C. Ice Cave

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.