岛屿数量
Problem Statement:
问题陈述:
A group of connected 1's forms an island. There is a matrix of N×M. You have to find out the numbers of item.
一组相连的1组成一个岛 。 有一个N×M的矩阵。 您必须找出项目编号。
Example:
例:
If there is a matrix:
如果存在矩阵:

Here three groups ones are possible. One is red one is yellow and one is blue.
Output: 3
在这里三组是可能的。 一是红色,一是黄色,一是蓝色。
输出3
Algorithm:
算法:
To solve this problem we follow this approach:
为了解决这个问题,我们采用以下方法:
We take a stack and whenever we find the first 1 we push the position into the stack and make that position visited.
我们取一个堆栈,每当找到第一个1时,我们就将该位置推入堆栈,并使该位置被访问。
Take the first element from the stack and pop from the stack.
从堆栈中取出第一个元素,然后从堆栈中弹出。
Check it's four neighbors. If out of them if anyone is 1 then we also push the position into the stack.
检查它是四个邻居。 如果其中任何一个为1,则我们还将位置推入堆栈。
Repeat the process until the queue is empty.
重复该过程,直到队列为空。
Count the numbers when the queue is empty and its give the island count.
计算队列为空时的数字,并给出孤岛计数。
C ++实现查找孤岛数 (C++ Implementation to find the number of islands)
#include <bits/stdc++.h>
using namespace std;
int x[] = { -1, 1, 0, 0 };
int y[] = { 0, 0, -1, 1 };
//check the validity of the position
//with respect to the matrix.
bool isvalid(int x_axis, int y_axis, int n)
{
return (x_axis >= 0 && x_axis < n && y_axis >= 0 && y_axis < n);
}
//function to count the no. of Island
int Island_count(int* arr, int n)
{
int count = 0;
stack<pair<int, int> > s;
set<pair<int, int> > st;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (*(arr + i * n + j) == 1 && st.find(make_pair(i, j)) == st.end()) {
//push the position with value 1 into the stack
s.push(make_pair(i, j));
//make the position visited
st.insert(make_pair(i, j));
while (!s.empty()) {
//take the top element of the stack
pair<int, int> p = s.top();
s.pop();
//check it's neighbours
for (int i = 0; i < 4; i++) {
int x_axis = p.first + x[i];
int y_axis = p.second + y[i];
//if the position is valid and it is not visited
//then push that position into stack
if (isvalid(x_axis, y_axis, n) && st.find(make_pair(x_axis, y_axis)) == st.end() && *(arr + x_axis * n + y_axis) == 1) {
s.push(make_pair(x_axis, y_axis));
st.insert(make_pair(x_axis, y_axis));
}
}
}
//every time when stack is empty means
//we visited all the group of 1's
count++;
}
}
}
return count;
}
int main()
{
int size = 4;
int arr[size][size] = { { 1, 1, 0, 0 }, { 1, 0, 1, 1 }, { 1, 1, 0, 1 }, { 0, 0, 1, 0 } };
cout << "No. Of Island is : ";
cout << Island_count(&arr[0][0], size) << endl;
return 0;
}
Output
输出量
The No. of Island is : 3
翻译自: https://www.includehelp.com/icp/find-the-number-of-islands.aspx
岛屿数量