题目意思
给出一个n * m的地图,起始点是S,终点E,中途#代表障碍物,无法走过。问能不能从起点走到终点。
解题思路
BFS走图题,别用dfs,规模一大就会暴毙。用了bfs的化应该就很简单了,这个题目本身没有难度,就是一个裸的模板题,如果还有不会的康康代码应该就懂了
#pragma GCC target("avx,sse2,sse3,sse4,popcnt") #pragma GCC optimize("O2,O3,Ofast,inline,unroll-all-loops,-ffast-math") #include <bits/stdc++.h> using namespace std; #define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0) #define all(vv) (vv).begin(), (vv).end() #define endl "\n" typedef long long ll; typedef unsigned long long ull; typedef long double ld; const ll MOD = 1e9 + 7; inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar()) s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; } inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-'); int cnt = 0; while (tmp > 0) { F[cnt++] = tmp % 10 + '0'; tmp /= 10; } while (cnt > 0)putchar(F[--cnt]); } inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; } ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; } inline int lowbit(int x) { return x & (-x); } const int N = 500 + 7; char mp[N][N]; bool vis[N][N]; int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1 }; int main() { int n, m; while (~scanf("%d %d", &n, &m)) { memset(vis, 0, sizeof(vis)); pair<int, int> st, ed; for (int i = 0; i < n; ++i) { scanf("%s", mp + i); for (int j = 0; j < m; ++j) if (mp[i][j] == 'S') st.first = i, st.second = j; else if (mp[i][j] == 'E') ed.first = i, ed.second = j; } queue<pair<int, int>> q; q.push(st); int flag = 0; while (q.size()) { pair<int, int> x = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int xx = x.first + dx[i], yy = x.second + dy[i]; if (xx < 0 or xx >= n or yy < 0 or yy >= m or mp[xx][yy] == '#' or vis[xx][yy]) continue; pair<int, int> y = make_pair(xx, yy); if (y == ed) { flag = 1; break; } q.push(y); vis[xx][yy] = 1; } if (flag) break; } if (flag) puts("Yes"); else puts("No"); } return 0; }