Please read the new rule regarding the restriction on the use of AI tools. ×

Gajanana's blog

By Gajanana, history, 10 months ago, In English

This is DIjkstra implementation on 2D matrix, each time checking for 4 directions (Up, down, left, right)

What are the time and space complexities for this code? Why?

Problem link : https://www.geeksforgeeks.org/problems/minimum-cost-path3833/1

Problem title "Minimum Cost Path" from gfg

Code link : https://ideone.com/behL3F

int minimumCostPath(vector<vector<int>>& grid) 
    {
        int n = grid.size(), m = grid[0].size();
        vector<vector<int>> cost(n,vector<int>(m,1e9));
        cost[0][0] = grid[0][0];
        
        priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, 
            greater<pair<int,pair<int,int>>>> pq;
        
        pq.push({cost[0][0],{0,0}});
        
        int row[] = {0,-1,0,1};
        int col[] = {1,0,-1,0};
        
        while(!pq.empty()){
            int cst = pq.top().first;
            int i = pq.top().second.first;
            int j = pq.top().second.second;
            pq.pop();
            
            for(int k=0;k<4;k++){
                int nr = i+row[k];
                int nc = j+col[k];
                
                if(nr<0 || nc<0 || nr>=n || nc>=m) continue;
                
                if(cost[nr][nc] > cst+grid[nr][nc]){
                    cost[nr][nc] = cst+grid[nr][nc];
                    pq.push({cost[nr][nc],{nr,nc}});
                }
            }
        }
        return cost[n-1][m-1];
    }

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

By Gajanana, history, 13 months ago, In English

Is Time Complexity O(N), O(2N) or something else, why?

Please tell me space complexity also for this.

   bool solve(Node *root1, Node *root2)
    {
        if(root1 == NULL && root2 == NULL)
            return true;

        if((root1 == NULL) || (root2 == NULL))
            return false;

        if(root1->data != root2->data)
            return false;

        bool v1 = myfunc(root1->left, root2->left);
        bool v2 = myfunc(root1->left, root2->right);
        bool v3 = myfunc(root1->right, root2->right);
        bool v4 = myfunc(root1->right, root2->left);

        return (v1 & v3) | (v2 & v4);
    }

    
    bool isIsomorphic(Node *root1, Node *root2)
    {
        return solve(root1, root2);
    }

Full text and comments »

  • Vote: I like it
  • +10
  • Vote: I do not like it