diff --git a/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/CMakeLists.txt b/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/CMakeLists.txt new file mode 100644 index 00000000..a9faeff1 --- /dev/null +++ b/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.14) +project(C) + +set(CMAKE_CXX_STANDARD 14) + +add_executable(C main.cpp) \ No newline at end of file diff --git a/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/main.cpp b/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/main.cpp new file mode 100644 index 00000000..8fd1bc34 --- /dev/null +++ b/1091-Shortest-Path-in-Binary-Matrix/cpp-1091/main.cpp @@ -0,0 +1,64 @@ +/// Source : https://leetcode.com/problems/shortest-path-in-binary-matrix/ +/// Author : liuyubobobo +/// Time : 2019-06-15 + +#include +#include +#include + +using namespace std; + + +/// BFS +/// Time Complexity: O(n * m) +/// Space Complexity: O(n * m) +class Solution { + +private: + const int d[8][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, + {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; + int n, m; + +public: + int shortestPathBinaryMatrix(vector>& grid) { + + if(grid[0][0]) return -1; + + n = grid.size(), m = grid[0].size(); + vector> res(n, vector(m, -2)); + + queue q; + res[0][0] = 0; + q.push(0); + while(!q.empty()){ + int x = q.front() / m; + int y = q.front() % m; + q.pop(); + + for(int i = 0; i < 8; i ++){ + int newX = x + d[i][0], newY = y + d[i][1]; + if(newX >= 0 && newX < n && newY >= 0 && newY < m && + grid[newX][newY] == 0 && res[newX][newY] == -2){ + res[newX][newY] = res[x][y] + 1; + q.push(newX * m + newY); + } + } + } + +// for(int i = 0; i < n; i ++){ +// for(int j = 0; j < m; j ++) +// cout << res[i][j] << " "; +// cout << endl; +// } + return res[n - 1][m - 1] + 1; + } +}; + + +int main() { + + vector> grid = {{0,0,0},{1,1,0},{1,1,0}}; + cout << Solution().shortestPathBinaryMatrix(grid) << endl; + + return 0; +} \ No newline at end of file diff --git a/readme.md b/readme.md index a51320b9..a5e965fa 100644 --- a/readme.md +++ b/readme.md @@ -741,4 +741,5 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com) | | | | | | | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [无] | [C++](1089-Duplicate-Zeros/cpp-1089/) | | | | 1090 | [Largest Values From Labels](https://leetcode.com/problems/largest-values-from-labels/) | [无] | [C++](1090-Largest-Values-From-Labels/cpp-1090/) | | | +| 1091 | [Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/) | [无] | [C++](1091-Shortest-Path-in-Binary-Matrix/cpp-1091/) | | | | | | | | | | \ No newline at end of file