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.
classSolution { public: intnumIslands(vector<vector<char>>& grid){ int row = grid.size(); if (!row) return0; int col = grid[0].size(); vector<vector<int> > dirs = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; // 4 directions of a position int res = 0; queue<pair<int, int>> que; //queue<int> q; x = curr / m; y = curr % m; // Traverse all points in the array for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == '1') { res++; grid[i][j] = '0'; // BFS que.push({i, j}); while (!que.empty()) { int m = que.front().first, n = que.front().second; // m - x coordinates, n - y coordinates que.pop(); for (auto dir : dirs) { int x = m + dir[0]; int y = n + dir[1]; if (x < 0 || y < 0 || x > row - 1 || y > col - 1 || grid[x][y] != '1') // x < 0 || y < 0 || x > row - 1 || y > col - 1 -- out of bounds, grid[x][y] != '1' -- not island continue; grid[x][y] = '0'; que.push({x, y}); } } } } } return res; } };