Skip to content

Commit

Permalink
1091 added.
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyubobobo committed Jun 16, 2019
1 parent 74a2f87 commit b86336a
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
6 changes: 6 additions & 0 deletions 1091-Shortest-Path-in-Binary-Matrix/cpp-1091/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.14)
project(C)

set(CMAKE_CXX_STANDARD 14)

add_executable(C main.cpp)
64 changes: 64 additions & 0 deletions 1091-Shortest-Path-in-Binary-Matrix/cpp-1091/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/// Source : https://leetcode.com/problems/shortest-path-in-binary-matrix/
/// Author : liuyubobobo
/// Time : 2019-06-15

#include <iostream>
#include <vector>
#include <queue>

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<vector<int>>& grid) {

if(grid[0][0]) return -1;

n = grid.size(), m = grid[0].size();
vector<vector<int>> res(n, vector<int>(m, -2));

queue<int> 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<vector<int>> grid = {{0,0,0},{1,1,0},{1,1,0}};
cout << Solution().shortestPathBinaryMatrix(grid) << endl;

return 0;
}
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -741,4 +741,5 @@ email: [[email protected]](mailto:[email protected])
| | | | | | |
| 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/) | | |
| | | | | | |

0 comments on commit b86336a

Please sign in to comment.