Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using namespace std;
- const int maxn = 1005;
- int n, m;
- char mat[maxn][maxn];
- void bfs(int si, int sj, int ei, int ej) {
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(0);
- vector<vector<bool>> visited(n, vector<bool>(m, false));
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- int shortest_dist = q.front();
- q.pop();
- if(ci == ei and cj == ej) {
- cout << shortest_dist << endl;
- return;
- }
- if(ci + 1 < n and mat[ci + 1][cj] != '#' and !visited[ci + 1][cj]) {
- q.push(ci + 1);
- q.push(cj);
- q.push(shortest_dist + 1);
- visited[ci + 1][cj] = true;
- }
- if(ci - 1 >= 0 and mat[ci - 1][cj] != '#' and !visited[ci - 1][cj]) {
- q.push(ci - 1);
- q.push(cj);
- q.push(shortest_dist + 1);
- visited[ci - 1][cj] = true;
- }
- if(cj + 1 < m and mat[ci][cj + 1] != '#' and !visited[ci][cj + 1]) {
- q.push(ci);
- q.push(cj + 1);
- q.push(shortest_dist + 1);
- visited[ci][cj + 1] = true;
- }
- if(cj - 1 >= 0 and mat[ci][cj - 1] != '#' and !visited[ci][cj - 1]) {
- q.push(ci);
- q.push(cj - 1);
- q.push(shortest_dist + 1);
- visited[ci][cj - 1] = true;
- }
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin >> n >> m;
- int si, sj, ei, ej;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- if(mat[i][j] == 'S') {
- si = i;
- sj = j;
- }
- if(mat[i][j] == 'E') {
- ei = i;
- ej = j;
- }
- }
- }
- bfs(si, sj, ei, ej);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment