To solve the problem of finding the number of lakes within islands in a grid, we can follow these steps:
- Iterate through each pixel in the grid.
- If we encounter a land pixel (represented by 'x'), we perform a depth-first search (DFS) to find all connected land pixels.
- During the DFS, we keep track of the number of separate islands we have encountered.
- If we encounter a lake pixel (represented by 'x') that is surrounded by different islands (i.e., it is not part of the same island as the current land pixel), we increment the lake count.
- We repeat the process until we have visited every pixel in the grid.
Test cases:
- A grid with all water pixels and no land pixels. In this case, we would expect the lake count to be 0.
- A grid with a single island and no lakes. In this case, we would expect the lake count to be 0.
- A grid with a single island and a single lake surrounded by that island. In this case, we would expect the lake count to be 1.
- A grid with multiple islands and multiple lakes, some of which are surrounded by different islands. In this case, we would expect the lake count to be greater than 1.
Here is a C++ solution that implements the above approach:
#include <iostream>
#include <vector>
using namespace std;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};
int n, lake_count;
vector<vector<bool>> visited, is_land;
void dfs(int x, int y) {
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < n) {
if (!visited[nx][ny] && is_land[nx][ny]) {
dfs(nx, ny);
} else if (visited[nx][ny] && !is_land[nx][ny]) {
lake_count++;
}
}
}
}
int main() {
cin >> n;
is_land.assign(n, vector<bool>(n, false));
visited.assign(n, vector<bool>(n, false));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
char c;
cin >> c;
if (c == 'x') {
is_land[i][j] = true;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!visited[i][j] && is_land[i][j]) {
dfs(i, j);
lake_count = 0;
}
}
}
cout << lake_count << endl;
return 0;
}
In this solution, we use a 2D vector visited to keep track of which pixels we have visited, and a 2D vector is_land to represent the grid. We also use a variable lake_count to keep track of the number of lakes we have encountered.
The dfs function performs a depth-first search to find all connected land pixels. We pass in the coordinates of the current pixel as arguments.
In the main function, we first read in the grid from standard input. We then iterate through each pixel in the grid and perform a DFS if we encounter a land pixel. During the DFS, we reset the lake_count variable to 0 and increment it every time we encounter a lake pixel that is surrounded by different islands.
Finally, we print out the lake_count variable as the result.