1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <iostream> #include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m; int g[N][N]; int d[N][N]; PII q[N * N];
int bfs(){ int hh = 0, tt = 0; q[0] = {0, 0}; memset(d, -1, sizeof d); d[0][0] = 0; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; while(hh <= tt){ auto t = q[hh++]; for(int i = 0; i < 4; i++){ int x = t.first + dx[i]; int y = t.second + dy[i]; if( x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){ d[x][y] = d[t.first][t.second] + 1; q[ ++ tt] = {x, y}; } } } return d[n - 1][m - 1]; }
int main(){ cin >> n >> m; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> g[i][j]; } } cout << bfs() << endl; return 0; }
#include <iostream> #include <queue> #include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m; queue<PII> q; int g[N][N]; int d[N][N];
int bfs(){ q.push({0, 0}); memset(d, -1, sizeof d); d[0][0] = 0; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; while(!q.empty()){ auto t = q.front(); q.pop(); for(int i = 0; i < 4; i++){ int x = t.first + dx[i]; int y = t.second + dy[i]; if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){ d[x][y] = d[t.first][t.second] + 1; q.push({x, y}); } } } return d[n - 1][m - 1]; }
int main(){ ios::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> g[i][j]; } } cout << bfs() <<endl; return 0; }
|