From 63eaa0fadf3867c187471c51c77699f12ad0ea51 Mon Sep 17 00:00:00 2001 From: Divyanshu Sharma <21bcs079@iiitdmj.ac.in> Date: Thu, 1 Jun 2023 22:48:34 +0530 Subject: [PATCH] I have added Solution of leetcode Problem 1091 --- .../1091- Shortest_Path_in_Binary_Matrix.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 LeetCode/1091- Shortest_Path_in_Binary_Matrix.cpp diff --git a/LeetCode/1091- Shortest_Path_in_Binary_Matrix.cpp b/LeetCode/1091- Shortest_Path_in_Binary_Matrix.cpp new file mode 100644 index 00000000..6487e6c1 --- /dev/null +++ b/LeetCode/1091- Shortest_Path_in_Binary_Matrix.cpp @@ -0,0 +1,36 @@ +// This is solution of Leetcode Problem : 1091. Shortest Path in Binary Matrix +// https://leetcode.com/problems/shortest-path-in-binary-matrix/description/ +// I have used BFS traversal approach here +// Time and Space Complexity both are O(n^2) here + +class Solution { +public: + int shortestPathBinaryMatrix(vector>& grid) { + int n = grid.size(); + if(grid[0][0]) return -1; + queue> q; + vector>seen(n , vector(n,false )); + seen[0][0] = true; + q.push({0 , 0}); + + while(!q.empty()){ + auto a=q.front(); q.pop(); + int i=a.first , j=a.second; + if(i==n-1 && j==n-1){ + return grid[i][j] + 1; + } + int I[] = {0 , 0 , 1 , 1 , 1, -1 , -1 , -1}; + int J[] = {1 , -1, 0 , -1, 1 , 0 , -1 , 1 }; + for(int p=0 ; p<8 ; p++){ + int x = i + I[p]; + int y = j + J[p]; + if(x>=0 && x=0 && y