题解:P13429 [GCJ 2009 Qualification] Watersheds

· · 题解

题面写得比较清晰了,这里就不再解释了。

思路

这道题使用深度优先搜索算法(dfs)。这道题的每一次搜索都最多往下递归一次(因为只会去找比它还低的位置),所以时间复杂度也不会太高。

dfs 也就是正常的写,没什么特殊的,从从当前格子出发,寻找四个方向中高度最低的邻居,如果有相同低的则按照题目中要求的顺序 —— 北、 西、 东、 南的第一个比它低的位置。最后按照水流的方法继续往下搜索。

然后我们需要确保同一流域的所有格子使用了相同的标记,如果水流向已标记的格子,就要进行合并,通过 color-- 减少颜色计数同时保证连通块的字典序正确。

:::success[正确代码] AC 记录

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e2+10;
int n,m,mp[N][N];
int vis[N][N]; //标记是否搜索过 
int dx[]={-1,0,0,1}; //按照题目给的顺序(北、 西、 东、 南) 
int dy[]={0,-1,1,0};
int color,nowcolor; //连通块的记号 
void dfs(int x,int y){
    bool found=false; //记录是否有比 (x,y) 更低的点 
    int nx=x,ny=y; //记录四周最低的坐标 
    for(int i=0;i<4;i++){
        int xx=x+dx[i],yy=y+dy[i]; //下一个位置的坐标 
        if(xx>0 && xx<=n && yy>=1 && yy<=m && mp[xx][yy]<mp[nx][ny]){ //判断位置合法其必现在的低 
            nx=xx;
            ny=yy;
            found=true; //找到了 
        }
    }
    if(!found) return; //没找到比我低的那就 return 
    if(vis[nx][ny]!=0){
        color--;
        nowcolor=vis[nx][ny];
    }else{
        vis[nx][ny]=nowcolor;
        dfs(nx,ny);
    }
    vis[x][y]=nowcolor; //同步颜色 
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin>>t; //t 组数据 
    for(int k=1;k<=t;k++){
        color=nowcolor=0;
        cout<<"Case #"<<k<<":"<<endl; //按照题目的输出格式 
        memset(vis,0,sizeof(vis)); //每一组数据一定要记得清空 
        cin>>n>>m;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                cin>>mp[i][j]; //输入地图 
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(vis[i][j]==0){
                    color++; //新连通块的记号 
                    nowcolor=color;
                    vis[i][j]=color;
                    dfs(i,j);
                }
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                cout<<char(vis[i][j]-1+'a')<<" ";
            }
            cout<<endl;
        }
    }
    return 0;
}

:::

完结撒花。