#include <bits/stdc++.h> using namespace std; // A function to check if a given cell (r, c) // can be included in BFS bool isSafe(vector<vector<char>>& grid, int r, int c, vector<vector<bool>>& vis) { int rows = grid.size(); int cols = grid[0].size(); return (r >= 0) && (r < rows) && (c >= 0) && (c < cols) && (grid[r][c] == 'L' && !vis[r][c]); } // Breadth-First-Search to visit all cells in the // current island void bfs(vector<vector<char>>& grid, vector<vector<bool>>& vis, int sr, int sc) { // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell vector<int> rNbr = { -1, -1, -1, 0, 0, 1, 1, 1 }; vector<int> cNbr = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Simple BFS first step, we enqueue // source and mark it as visited queue<pair<int, int>> q; q.push({sr, sc}); vis[sr][sc] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their unvisited adjacent while (!q.empty()) { int r = q.front().first; int c = q.front().second; q.pop(); // Go through all 8 adjacent for (int k = 0; k < 8; k++) { int newR = r + rNbr[k]; int newC = c + cNbr[k]; if (isSafe(grid, newR, newC, vis)) { vis[newR][newC] = true; q.push({newR, newC}); } } } } // This function returns the number of islands // (connected components) in a graph int countIslands(vector<vector<char>>& grid) { // Mark all cells as not visited int rows = grid.size(); int cols = grid[0].size(); vector<vector<bool>> vis(rows, vector<bool>(cols, false)); // Call BFS for every unvisited vertex // Whenever we see an unvisited vertex, // we increment res (number of islands) // also. int res = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (grid[r][c] == 'L' && !vis[r][c]) { bfs(grid, vis, r, c); res++; } } } return res; } int main() { vector<vector<char>> grid = { { 'L', 'L', 'W', 'W', 'W' }, { 'W', 'L', 'W', 'W', 'L' }, { 'L', 'W', 'W', 'L', 'L' }, { 'W', 'W', 'W', 'W', 'W' }, { 'L', 'W', 'L', 'L', 'W' } }; cout << countIslands(grid) << endl; return 0; }