From fc18020e02bed6591adf7cbd77d36e42ec1528b4 Mon Sep 17 00:00:00 2001 From: Kiritow <1362050620@qq.com> Date: Sat, 22 May 2021 16:22:48 +0800 Subject: [PATCH] Add leetcode 1293 --- LeetCode/1293.cpp | 100 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 LeetCode/1293.cpp diff --git a/LeetCode/1293.cpp b/LeetCode/1293.cpp new file mode 100644 index 0000000..91d2e03 --- /dev/null +++ b/LeetCode/1293.cpp @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +// Leetcode 1293 + +struct Plan +{ + int x, y, k, s; + + Plan(int X, int Y, int K, int S) : x(X), y(Y), k(K), s(S) { } +}; + +class Solution { +public: + int shortestPath(vector>& grid, int k) { + queue todo; + + todo.emplace(Plan(0, 0, k, 0)); + vector> visited; + int ymax = -1; + for (int i = 0; i < grid.size(); i++) + { + vector vec(grid[i].size(), -1); + ymax = grid[i].size(); + visited.push_back(vec); + } + int xmax = grid.size(); + + int minSteps = INT_MAX; + + while (!todo.empty()) + { + Plan c = todo.front(); + todo.pop(); + visited[c.x][c.y] = c.k; + + if (c.x == xmax - 1 && c.y == ymax - 1) + { + minSteps = min(c.s, minSteps); + continue; + } + + if (c.y + 1 < ymax && c.k > visited[c.x][c.y + 1] && grid[c.x][c.y + 1] == 0) + { + todo.emplace(Plan(c.x, c.y + 1, c.k, c.s + 1)); + visited[c.x][c.y + 1] = c.k; + } + if (c.y + 1 < ymax && c.k > visited[c.x][c.y + 1] && grid[c.x][c.y + 1] == 1 && c.k > 0) + { + todo.emplace(Plan(c.x, c.y + 1, c.k - 1, c.s + 1)); + visited[c.x][c.y + 1] = c.k; + } + + if (c.y > 0 && c.k > visited[c.x][c.y - 1] && grid[c.x][c.y - 1] == 0) + { + todo.emplace(Plan(c.x, c.y - 1, c.k, c.s + 1)); + visited[c.x][c.y - 1] = c.k; + } + if (c.y > 0 && c.k > visited[c.x][c.y - 1] && grid[c.x][c.y - 1] == 1 && c.k > 0) + { + todo.emplace(Plan(c.x, c.y - 1, c.k - 1, c.s + 1)); + visited[c.x][c.y - 1] = c.k; + } + + if (c.x + 1 < xmax && c.k > visited[c.x + 1][c.y] && grid[c.x + 1][c.y] == 0) + { + todo.emplace(Plan(c.x + 1, c.y, c.k, c.s + 1)); + visited[c.x + 1][c.y] = c.k; + } + if (c.x + 1 < xmax && c.k > visited[c.x + 1][c.y] && grid[c.x + 1][c.y] == 1 && c.k > 0) + { + todo.emplace(Plan(c.x + 1, c.y, c.k - 1, c.s + 1)); + visited[c.x + 1][c.y] = c.k; + } + + if (c.x > 0 && c.k > visited[c.x - 1][c.y] && grid[c.x - 1][c.y] == 0) + { + todo.emplace(Plan(c.x - 1, c.y, c.k, c.s + 1)); + visited[c.x - 1][c.y] = c.k; + } + if (c.x > 0 && c.k > visited[c.x - 1][c.y] && grid[c.x - 1][c.y] == 1 && c.k > 0) + { + todo.emplace(Plan(c.x - 1, c.y, c.k - 1, c.s + 1)); + visited[c.x - 1][c.y] = c.k; + } + } + + if (minSteps == INT_MAX) + { + return -1; + } + return minSteps; + } +}; \ No newline at end of file