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
| struct F { int x, y, c; F(int x, int y, int c): x(x), y(y), c(c) {} }; class Solution { private: static constexpr int ds[5] = {1, 0, -1, 0, 1}; public: int shortestPath(vector<vector<int>>& grid, int k) { int m = grid.size(), n = grid[0].size(); if (m == 1 && n == 1) return 0; if (k >= m + n - 3) return m + n - 2; bool vis[m][n][k + 1]; memset(vis, false, sizeof(vis)); queue<F> q; q.emplace(0, 0, k); vis[0][0][k] = true; int step = 0; while (q.size()) { ++step; int size = q.size(); while (size--) { auto [x, y, c] = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int nx = x + ds[i], ny = y + ds[i + 1]; if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue; if (nx == m - 1 && ny == n - 1) return step; if (grid[nx][ny] == 0) { if (vis[nx][ny][c]) continue; q.emplace(nx, ny, c); vis[nx][ny][c] = true; } else if (c > 0 && !vis[nx][ny][c - 1]) { q.emplace(nx, ny, c - 1); vis[nx][ny][c - 1] = true; } } } } return -1; } };
|