diff --git a/JP Morgan/problem9.md b/JP Morgan/problem9.md index 73e8cb2..d6cd9d2 100644 --- a/JP Morgan/problem9.md +++ b/JP Morgan/problem9.md @@ -2,33 +2,29 @@ ## Problem Description - Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. - - Example 1: Input: grid = [ - ["1","1","1","1","0"], - ["1","1","0","1","0"], - ["1","1","0","0","0"], - ["0","0","0","0","0"] +["1","1","1","1","0"], +["1","1","0","1","0"], +["1","1","0","0","0"], +["0","0","0","0","0"] ] Output: 1 Example 2: Input: grid = [ - ["1","1","0","0","0"], - ["1","1","0","0","0"], - ["0","0","1","0","0"], - ["0","0","0","1","1"] +["1","1","0","0","0"], +["1","1","0","0","0"], +["0","0","1","0","0"], +["0","0","0","1","1"] ] Output: 3 - Constraints: @@ -37,3 +33,49 @@ Constraints: - 1 <= m, n <= 300 - grid[i][j] is '0' or '1'. +/// C++ Solution + +class Solution { +public: + + void bfs(int row,int col,vector> &vis,vector>&grid){ + vis[row][col]=1; + queue> q; + q.push({row,col}); + int n = grid.size(); + int m = grid[0].size(); + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + + while(!q.empty()){ + int row = q.front().first; + int col = q.front().second; + q.pop(); + for (auto [dr,dc] : directions){ + int nrow = row + dr ; + int ncol = col + dc ; + if(nrow >=0 && nrow < n && ncol >= 0 && ncol >& grid) { + int n = grid.size(); + int m = grid[0].size(); + vector>vis(n,vector(m,0)); + int count = 0 ; + for(int row = 0 ; row= 0 && r < n){ + if(s[l] == s[r]){ + l--; r++; + }else + break; + } + int len = r-l-1; + if(len > max_len){ + max_len = len; + st = l+1; + end = r-1; + } + } + + // Even length + for(int i = 0; i < n-1; ++i){ + int l = i, r = i+1; + while(l >= 0 && r < n){ + if(s[l] == s[r]){ + l--; r++; + }else + break; + } + int len = r-l-1; + if(len > max_len){ + max_len = len; + st = l+1; + end = r-1; + } + } + + return s.substr(st, max_len); + + } +}; + +