题目描述
You are given an �×�n×m grid �a of non-negative integers. The value ��,�ai,j represents the depth of water at the �i -th row and �j -th column.
A lake is a set of cells such that:
- each cell in the set has ��,�>0ai,j>0 , and
- there exists a path between any pair of cells in the lake by going up, down, left, or right a number of times and without stepping on a cell with ��,�=0ai,j=0 .
The volume of a lake is the sum of depths of all the cells in the lake.
Find the largest volume of a lake in the grid.
输入格式
The first line contains a single integer �t ( 1≤�≤1041≤t≤104 ) — the number of test cases.
The first line of each test case contains two integers �,�n,m ( 1≤�,�≤10001≤n,m≤1000 ) — the number of rows and columns of the grid, respectively.
Then �n lines follow each with �m integers ��,�ai,j ( 0≤��,�≤10000≤ai,j≤1000 ) — the depth of the water at each cell.
It is guaranteed that the sum of �⋅�n⋅m over all test cases does not exceed 106106 .
输出格式
For each test case, output a single integer — the largest volume of a lake in the grid.
题意翻译
给定 �×�n×m 的矩阵,正整数上、下、左、右相连构成一个连通块。定义一个连通块的权值为该连通块中所有数的和。求矩阵中最大的连通块。
Translated by @JYqwq
输入输出样例
输入 #1复制
5 3 3 1 2 0 3 4 0 0 0 5 1 1 0 3 3 0 1 1 1 0 1 1 1 1 5 5 1 1 1 1 1 1 0 0 0 1 1 0 5 0 1 1 0 0 0 1 1 1 1 1 1 5 5 1 1 1 1 1 1 0 0 0 1 1 1 4 0 1 1 0 0 0 1 1 1 1 1 1
输出 #1复制
10 0 7 16 21
分析:
大致给大家翻译一下,就是给你一个二维数组当做地图,地图中有诸多个湖,是湖的每一个点的数值代表着湖的这一点的深度,整个湖的深度是所有点的深度和,0代表陆地。让你输出这张地图中最深的湖的深度。
这个题呢难点主要就一个,那就是在什么情况下去搜索。
对于这个问题呢,我们先把map都输入进去,然后再去遍历,当遍历到一个点不是0的时候,是不是就代表着我们遇到了一个湖,对不对,然后我们就以这一个点为突破,开始bfs,然后在bfs的时候呢,不断记录每个湖的深度记录下来,记录下之后呢,千万别忘了让他变成零,防止我们后续寻找下一个湖的时候找到的是同一个湖。总而言之就是遍历的时候遇到了一个湖,开始bfs记录湖的深度,然后把这个湖填平变成0,再继续往下遍历map,再遇到一个数不是0那就说明遇到了另一个湖...最后选出一个最大的深度就好。
至于怎么把一个点存到queue里边呢,我在这是用了两个queue分别存储x和y,不理解的同学可以去看一看我 《好奇怪的游戏》那一篇文章。
OK!上代码!
代码:
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
queue<int>q_x;//存放点的x
queue<int>q_y;//存放点的y
int num, n, m, ans, mmax;
int map[1050][1050];
int xrr[4] = { 1,-1,0,0 };//上下左右移动
int yrr[4] = { 0,0,1,-1 };
int bfs(int x, int y)
{
int res = map[x][y];//初始化湖的深度
map[x][y] = 0;//记录后就归为0避免重复记录
while (q_x.size())
{
for (int i = 0; i < 4; i++)
{
int tx = q_x.front() + xrr[i];
int ty = q_y.front() + yrr[i];
if (tx<1 || tx>n || ty<1 || ty>m)
continue;
if (map[tx][ty] == 0)
continue;
q_x.push(tx);
q_y.push(ty);
res += map[tx][ty];//更新深度
map[tx][ty] = 0;//记录后归为0
}
q_x.pop();
q_y.pop();
}
return res;
}
int main()
{
cin >> num;
for (int i = 1; i <= num; i++)
{
memset(map, 0, sizeof(map));//别忘了每次重置一下map
mmax = 0;
ans = 0;
cin >> n >> m;
for (int j = 1; j <= n; j++)
for (int k = 1; k <= m; k++)
cin >> map[j][k];
if (n == 1 && m == 1)//别忘了特判一下地图就一个点的时候
{
cout << map[1][1] << endl;
continue;
}
for (int j = 1; j <= n; j++)
{
for (int k = 1; k <= m; k++)
{
if (map[j][k] != 0)//如果遇到湖了
{
q_x.push(j);
q_y.push(k);
mmax = max(mmax, bfs(j, k));//更新最大值
}
}
}
cout << mmax << endl;
}
return 0;
}