【发布时间】:2014-06-20 22:41:12
【问题描述】:
问题:
这是一个面试问题。
一群农民有一些海拔数据,我们将帮助他们了解降雨如何流经他们的农田。
我们将土地表示为高度的二维数组,并使用以下模型,基于水流下山的想法:
如果一个小区的八个相邻小区都有更高的海拔,我们称这个小区为盆地;水收集在盆地中。
否则,水会流向海拔最低的相邻单元格。
直接或间接流入同一水槽的细胞被称为同一盆地的一部分。
下面是几个例子:
输入:
1 1 2
1 1 7
3 6 9
尺寸 4
9 9 9 8 7 7
8 8 7 7 7 8
8 8 8 7 7 7
8 8 8 9 9 9
8 8 8 7 7 7
4 4 5 5 5 5
5 5 5 6 6 7
5 5 5 8 8 6
8 号
9 9 9 8 8 8
8 8 8 7 7 7
7 7 7 7 7 7
8 8 8 8 9 9
5 5 5 5 6 3
5 5 5 3 3 3
9 号
突出显示的值形成最大尺寸的盆地。
所以问题是
将地图划分为盆地。特别是,给定海拔地图,您的代码应将地图划分为盆地并输出最大盆地的大小。 我们需要突出显示最大尺寸的盆地。
如果问题有这个假设
“如果一个cell不是sink,你可以假设它有一个唯一的最低邻居,并且这个邻居将低于cell”
那我可以想到这个解决方案
Each array element is a node in a graph. Construct the graph adding edges between the nodes:
1 If node A is the smallest among all of its own neighbors, don't add an edge (it's a sink)
2 There is an edge between two neighbors A and B iff A is the smallest of all neighbors of B.
3 Finally traverse the graph using BFS or DFS and count the elements in the connected components.
到目前为止,我已经实现了算法的第三部分
#include<iostream>
#include<vector>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
int cv[1000]; // array stores number of nodes in each connected components
int main()
{
queue<int>q;
bool visited[100000];
int t,i,j,x,y,cvindex=0;
int n,e;
cin>>t;
while(t--)
{
scanf("%d%d",&n,&e);
vector< vector<int> >G(n);
memset(visited,0,sizeof(visited));
for(i=0;i<e;i++)
{
scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}
int ans=0;
for(i=0;i<n;i++)
{
if(!visited[i])
{
q.push(i);
visited[i]=1;
cv[cvindex]++;
while(!q.empty())
{
int p=q.front();
q.pop();
for(j=0;j<G[p].size();j++)
{
if(!visited[G[p][j]])
{
visited[G[p][j]]=1;
q.push(G[p][j]);
cv[cvindex]++;
}
}
}
ans++;
cvindex++;
}
}
printf("%d\n",ans);
sort(cv,cv+cvindex);
for(int zz=0;zz<cvindex;zz++)
printf("%d ",cv[zz]);
}
}
时间复杂度 O(n*m)
但是如何在没有假设的情况下解决上述问题? 我想要几乎相似的方法,稍作修改。
欢迎使用其他算法。
而且在时间复杂度方面是否存在更好的算法?
【问题讨论】:
-
一个盆地怎么有任何尺寸 > 1 如果需要它有八个更高的邻居
-
我不明白你想问什么?是的,一个节点可以有 8 个相邻节点。
-
@Ben 指的是:“如果一个小区的八个相邻小区都有更高的海拔,我们称这个小区为盆地”。鉴于该定义,盆地的大小始终为 1。
-
@IInspectable,不一定:它描述了一种可能的情况,而不是全部。在那一行中没有说 8 个更高的节点是必需的。
-
@Ben: 没必要,你可以查看示例 2 和示例 3,其中盆地没有尺寸 1
标签: c++ arrays algorithm graph