3个TLE

P2385 [USACO07FEB] Bronze Lilypad Pond B

chenxuanting @ 2020-04-27 13:16:15

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int n,m,stepx,stepy;
int a[35][35];
int vis[35][35];
int ans=0x3fffffff;
int posx,posy;
void dfs(int x,int y,int step)
{
    if(x<1||y<1||x>n||y>m){
        return;
    }
    if(step>ans||step>n*m){
        return;
    }
    if(a[x][y]==0||a[x][y]==2){
        return;
    }
    if(vis[x][y]==1){
        return;
    }
    if(a[x][y]==4){
        ans=min(ans,step);
        return;
    }
    vis[x][y]=1;
    dfs(x+stepx,y+stepy,step+1);
    dfs(x-stepx,y+stepy,step+1);
    dfs(x+stepx,y-stepy,step+1);
    dfs(x-stepx,y-stepy,step+1);
    dfs(x+stepy,y+stepx,step+1);
    dfs(x-stepy,y+stepx,step+1);
    dfs(x+stepy,y-stepx,step+1);
    dfs(x-stepy,y-stepx,step+1);
    vis[x][y]=0;
    return;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>stepx>>stepy;
    for(int i=1;i<=n;i++){
        for(int i1=1;i1<=m;i1++){
            cin>>a[i][i1];
            if(a[i][i1]==3){
                posx=i;
                posy=i1;
            }
        }
    }
    dfs(posx,posy,0);
    cout<<ans;
    return 0;
}

by chenxuanting @ 2020-04-27 13:16:27

希望更丰富的展现?使用Markdown


by Semsue @ 2020-04-27 13:32:15

为什么不用bfs?


by Semsue @ 2020-04-27 13:34:01

或者加个记忆化


by pocafup @ 2020-04-27 13:41:19

记搜吧,这个明显过不去。


by 老子是北瓜 @ 2020-04-27 13:58:06

这么搜的估计是刚学搜索


by JeffWang2019 @ 2020-04-27 14:00:23

@chenxuanting 请使用bfs


by JeffWang2019 @ 2020-04-27 14:01:02

@chenxuanting 参考马的遍历


by chenxuanting @ 2020-04-27 14:45:57

@老子是白菜

我学了很久的搜索,只能说wtcl


by chenxuanting @ 2020-04-29 17:09:08

已过


|