Atcoder ATC001A depth priority search implemented in C++ using recursive results in TLE

Asked 2 years ago, Updated 2 years ago, 36 views

ATC001A depth priority search was implemented in C++ as follows, but 12 out of 88 TLE and 2 MLE were implemented.
Recursive is used.
I also gave the coordinates of goal to the argument and tried to return when v=goal, but it didn't work.
How can I fix it?

#include<bits/stdc++.h>
using namespace std;

vector<vector<int>>dxdy={1,0}, {-1,0}, {0,1}, {0,-1}};

void dfs(vector<string>c, inth, intw, vector>int>v, vector<bool>>>>seen){
    see [v[0]][v[1]]=true;

    for(inti=0;i<4;i++){
        int nxtX=v[0]+dxdy[i][0], nxtY=v[1]+dxdy[i][1];

        if(nxtX<0||nxtY<0||nxtX>=h||nxtY>=w) continue;
        if(seen[nxtX][nxtY]) continue;
        if(c[nxtX][nxtY]=='#') continue;
        dfs(c,h,w,{nxtX,nxtY},seen);
    }
}

int main() {
    inth,w;
    cin>>h>>w;
    vector<string>c(h);
    vector<int>start(2), goal(2);

    for(inti=0;i<h;i++){
        cin>>c[i];
        for(int j=0;j<w;j++){
            if(c[i][j]=='s') start={i,j};
            else if(c[i][j]=='g') goal={i,j};
        }
    }
    vector<vector>bool>>seen(h,vector<int>(w, false));

    dfs(c,h,w,start,seen);

    if(seen[goal[0]][goal[1]])cout<<"Yes"<<
    else cout <<"No" <<endl;
}

c++ algorithm

2022-09-29 21:35

1 Answers

Because dfs passes the value of c, it may be because the contents of c are copied every time a function is called. Try rewriting it to a reference pass, such as seen.

If you think about the calculated amount, each time you visit O(n^2) compartments, you spend O(n^2) time on copying, so it takes O(n^4) overall, and you can't meet the runtime limit.In particular, if the input contains a long path with one end of the house, the recursion is deep and the memory is exhausted in a copy of c, which is likely to cause MLE.


2022-09-29 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.