CSES Labyrinth : time limit is exceeding in one test case

Revision en1, by salt_n_ice, 2020-11-27 07:38:20

Here is my implementation: * Here, sn and en stands for starting node and ending node respectively, and mini_map is the 2d array showing path of shortest distance from starting node to all other reachable nodes. Rest is Breadth-First Search.

I don't see whats making this solution so long

char a[1001][1001];
bool visited[1001][1001];
char mini_map[1001][1001];
bool valid(int i, int j)
{
    if(i>=0 && i<n && j>=0 && j<m && a[i][j]!=-1 && visited[i][j]==false) return true;
    else return false;
}
void solve() {
    cin>>n>>m;
    for(int i=0; i<n; ++i)
    {
        for(int j=0; j<m; ++j)
        {
            char x;
            cin>>x;
            if(x=='.')a[i][j]=0;
            else if(x=='#') a[i][j]=-1;
            else if(x=='A')
            {
                a[i][j]=1;
                sn_i = i;
                sn_j = j;
            }
            else
            {
                a[i][j]=2;
                en_i = i;
                en_j = j;
            }
            visited[i][j]=false;
            mini_map[i][j]='0';
        }
    }
    queue<pair<int, int> > q;
    q.push({sn_i, sn_j});
    while(!q.empty())
    {
        pair<int, int> s = q.front();
        int sf = s.first, ss = s.second;
        q.pop();
        if(valid(sf+1,ss))
        {
            visited[sf+1][ss] = true;
            mini_map[sf+1][ss] = 'D';
            q.push({sf+1,ss});
        }
        if(valid(sf-1,ss))
        {
            visited[sf-1][ss]=true;
            mini_map[sf-1][ss]='U';
            q.push({sf-1,ss});
        }
        if(valid(sf,ss+1))
        {
            visited[sf][ss+1]=true;
            mini_map[sf][ss+1]='R';
            q.push({sf,ss+1});
        }
        if(valid(sf,ss-1))
        {
            visited[sf][ss-1]=true;
            mini_map[sf][ss-1]='L';
            q.push({sf,ss-1});
        }
    }
    int cnt = 0;
    string res = "";
    int i=en_i, j = en_j;
    while(i!=sn_i || j!=sn_j)
    {
        char x = mini_map[i][j];
        if(x=='R') j--;
        else if(x=='L') j++;
        else if(x=='U') i++;
        else if(x=='D') i--;
        else
        {
            cout<<"NO"<<endl;
            return;
        }
        res = x+res;
        cnt++;
    }
    cout<<"YES"<<endl<<cnt<<endl<<res<<endl;
}
Tags #graph, #bfs, time complexity, #c++

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English salt_n_ice 2020-11-27 09:47:20 147
en4 English salt_n_ice 2020-11-27 09:36:01 56 Tiny change: 'Here is my' -> '[Problem Link](https://cses.fi/problemset/task/1193)\n\nHere is my'
en3 English salt_n_ice 2020-11-27 09:33:05 5 Tiny change: '="Code">\n...\n~~~~~\nc' -> '="Code">\n~~~~~\nc'
en2 English salt_n_ice 2020-11-27 09:32:15 47
en1 English salt_n_ice 2020-11-27 07:38:20 2451 Initial revision (published)