题目:
Given a 2d m * n grid map of ’1’s (land) and ’0’s (water), count 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.
INPUT:
Line 1: m and n.
Line 2: ’1’ or ’0’ in grid and split by spaces
OUTPUT:
Line 1: number of islands.
代码:
#include<iostream>
#include<vector>
using namespace std;
void affect(vector<vector<int>>& v,int i,int j) {
if ( i >= v.size() || j >= v[0].size() || i < 0 || j < 0|| v[i][j] == 0)return;
v[i][j] = 0;
affect(v, i + 1, j);
affect(v, i - 1, j);
affect(v, i, j + 1);
affect(v, i, j - 1);
}
int main() {
int m,n;
cin >>m>> n;
vector<vector<int>> v(m, vector<int>(n, 0));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> v[i][j];
}
}
//v = { {1,1,1,1,0},{1,1,0,1,0},{1,1,0,0,0},{0,0,0,0,0} };
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (v[i][j] == 1) {
count++;
affect(v, i, j);
}
}
}
cout << count;
int c;
cin >> c;
return 0;
}