Given a grid of size n*m (n is number of rows and m is number of columns grid has) consisting of ‘0’s(Water) and ‘1’s(Land). Find the number of islands.
Note: An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically or diagonally i.e., in all 8 directions.
classSolution { voidbfs(vector<vector<char>>& grid, int sy, int sx, int n, int m){ int dy[8]{-1,-1,-1,0,1,1,1,0}, dx[8]{-1,0,1,1,1,0,-1,-1}; queue<pair<int, int>> q; q.push({sy, sx}); grid[sy][sx] = '0'; while(!q.empty()) { auto p = q.front(); q.pop(); auto y = p.first, x = p.second; for(int i = 0; i < 8; i++) { int ny = y + dy[i], nx = x + dx[i]; if(0 <= ny and ny < n and0 <= nx and nx < m and grid[ny][nx] == '1') { grid[ny][nx] = '0'; q.push({ny,nx}); } } } } public: // Function to find the number of islands. intnumIslands(vector<vector<char>>& grid){ int n = grid.size(), m = grid[0].size(); int res = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] == '1') { bfs(grid, i, j, n, m); res++; } } } return res; } };