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
| class Solution { public: bool findSafeWalk(vector<vector<int>>& grid, int health) { int n = static_cast<int>(grid.size()); int m = static_cast<int>(grid[0].size());
const static std::vector<int> dx {1, 0, -1, 0}; const static std::vector<int> dy {0, 1, 0, -1};
std::vector<std::vector<std::vector<bool>>> visited(n, std::vector<std::vector<bool>>(m, std::vector<bool>(health + 1)));
std::queue<std::array<int, 3>> q; q.push({0, 0, health - grid[0][0]}); visited[0][0][health] = true;
while (!q.empty()) { auto [x, y, h] = q.front(); q.pop(); if (h <= 0) { continue; } if (x == n - 1 and y == m - 1) { return true; }
for (int i = 0; i < 4; i += 1) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx < 0 or nx >= n or ny < 0 or ny >= m or h - grid[nx][ny] <= 0 or visited[nx][ny][h - grid[nx][ny]]) { continue; } q.push({nx, ny, h - grid[nx][ny]}); visited[nx][ny][h - grid[nx][ny]] = true; } }
return false; } };
|