• AcWing每日一题--献给阿尔吉侬的花束


    https://www.acwing.com/problem/content/1103/

    搜索题,数据范围为1<=n,m<=200。

    所以dfs是必然超时的,时间复杂度为(200*200)!

     1 void dfs(PII now,PII e,int step){
     2     if(now==e){
     3         res=min(res,step);
     4         return ;
     5     }
     6     for(int i=0;i<4;i++){
     7         int x=now.x+u[i],y=now.y+v[i];
     8         if(x>=0&&x<n&&y>=0&&y<m&&g[x][y]!='#'){
     9             g[x][y]='#';
    10             dfs({x,y},e,step+1);
    11             g[x][y]='.';
    12         }
    13     }
    14 }

    所以得用bfs,时间复杂度为200*200。

     1 #include<iostream>
     2 #include<climits>
     3 #include<queue>
     4 #include<cstring>
     5 using namespace std;
     6 typedef pair<int,int> PII;
     7 const int N=210;
     8 char g[N][N];
     9 int n,m;
    10 int u[]={-1,0,1,0};
    11 int v[]={0,1,0,-1};
    12 int dist[N][N];
    13 int bfs(PII s,PII e){
    14     memset(dist,-1,sizeof(dist));
    15     queue<PII> q;
    16     q.push(s);
    17     dist[s.first][s.second]=0;
    18     while(q.size()){
    19         PII t=q.front();
    20         q.pop();
    21         for(int j=0;j<4;j++){
    22             int x=t.first+u[j],y=t.second+v[j];
    23             if(x<0||x>=n||y<0||y>=m||g[x][y]=='#')
    24                 continue;
    25             if(dist[x][y]!=-1)
    26                 continue;
    27             dist[x][y]=dist[t.first][t.second]+1;
    28             if(make_pair(x,y)==e){
    29                 return dist[x][y];
    30             }
    31             q.push({x,y});
    32         }
    33     }
    34     return -1;
    35 }
    36 int main(void){
    37     int t;
    38     cin>>t;
    39     while(t--){
    40        cin>>n>>m;
    41        PII start,end;
    42        for(int i=0;i<n;i++){
    43            for(int j=0;j<m;j++){
    44                cin>>g[i][j];
    45                if(g[i][j]=='S') start={i,j},g[i][j]='#';
    46                if(g[i][j]=='E') end={i,j};
    47            }
    48        }
    49        int res=bfs(start,end);
    50        if(res!=-1) cout<<res<<endl;
    51        else cout<<"oop!"<<endl;
    52     }
    53     return 0;
    54 }
  • 相关阅读:
    HDU 1251 统计难题
    HDU 1212 Big Number
    HDU 1205 吃糖果
    HDU 5776 Sum
    19 中山重现赛 1002 triangle
    7.29 线段树扫描线 ,矩形扫描
    一个很好的主席树总结
    7.14 单调栈 单调队列 +dp优化
    7.14 一个烦人的bug:dp[ q[tail] ] ---> dp[ tail ]
    7.13 cf573 补题
  • 原文地址:https://www.cnblogs.com/greenofyu/p/14367236.html
Copyright © 2020-2023  润新知