L2-048 寻宝图
喔,太久没敲代码了,有点生疏了。
baozang[i]=1:第i块岛屿有宝藏。
baozang[i]=0: 第i块岛屿没有宝藏。
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> area;
int row, col;
int dx[4] = { 0,0,-1,1};
int dy[4] = { -1,1,0,0 };
int baozang[100010],cnt=0;
void dfs(int x,int y) {
if (area[x][y]==0) return;//遇到了水
if (area[x][y] >= 2 && area[x][y] <= 9) {//发现了宝藏
baozang[cnt] = 1;//有宝藏的岛屿
}
area[x][y] = 0;
for (int i = 0; i < 4; i++) {
int xx = dx[i] + x;
int yy = dy[i] + y;
if (xx >= 1 && xx <= row && yy >= 1 && yy <= col) {
dfs(xx, yy);
}
}
}
int main() {
cin >> row >> col;
area.resize(row+10);
for (int i = 0; i < row + 10; i++) {
area[i].resize(col+10);
}
cin.get();
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
char c;
c = cin.get();
area[i][j] = c - '0';
}
cin.get();
}
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
if (area[i][j]!=0) {
dfs(i,j);
cnt++;//岛屿的数量
}
}
}
int res = 0;
for (int i = 0; i < cnt; i++) {
if (baozang[i]) res++;
}
cout << cnt << " " << res << '\n';
return 0;
}