gg
unknown
c_cpp
2 years ago
1.3 kB
2
Indexable
Never
//3 #include "bits/stdc++.h" using namespace std; const int N = 100 + 5; char grid[N][N]; bool vis[N][N]; int dis[N][N]; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; signed main() { ios_base::sync_with_stdio(false), cin.tie(nullptr); int n, m; cin >> n >> m; memset(dis, 0x3f3f3f, sizeof dis); memset(vis, 0, sizeof vis); for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { cin >> grid[i][j]; } } vis[0][0] = true; dis[0][0] = 0; queue <pair<int, int>> q; q.push({0,0}); auto isValid = [=] (int r, int c) { if(r < 0 or r >= n) return false; if(c < 0 or c >= m) return false; if(grid[r][c] == '#') return false; return true; }; while(!q.empty()) { auto now = q.front(); q.pop(); for(int i = 0; i < 4; ++i) { pair<int, int> next = {now.first + dx[i], now.second + dy[i]}; if(isValid(next.first, next.second) and !vis[next.first][next.second]) { q.push(next); vis[next.first][next.second] = true; dis[next.first][next.second] = dis[now.first][now.second] + 1; } } } cout << (dis[n - 1][m - 1] >= int (0x3f3f3f) ? -1 : dis[n - 1][m - 1]) << '\n'; }