C++ || Using BFS & Priority Queue
\n### Do Upvote if Helpful :-)\nclass Solution {\n    int n,m;\n    int d[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};\npublic:\n    \n    bool valid(int a,int b,int n,
\n### Do Upvote if Helpful :-)\nclass Solution {\n    int n,m;\n    int d[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};\npublic:\n    \n    bool valid(int a,int b,int n,int m){\n        \n        return (a>=0&&a<n&&b>=0&&b<m);\n    }\n    \n    int bfs(vector<vector<int>> &fo,pair<int,int> start,pair<int,int> target){\n        \n        if(start.first==target.first && start.second==target.second)\n            return 0;\n        \n        vector<vector<bool>> used(n,vector<bool>(m,false));\n        used[start.first][start.second] = true;\n        \n        int steps = 0;\n        queue<pair<int,int>> q;\n        \n        q.push(start);\n        while(!q.empty()){\n            \n            steps++;\n            int size = q.size();\n           \n            while(size--){\n                auto curr = q.front();\n                q.pop();\n                \n                for(int i=0;i<4;i++){\n                    int x = curr.first+d[i][0];\n                    int y = curr.second+d[i][1];\n                    \n                    if(valid(x,y,n,m) && !used[x][y] && fo[x][y]>0){\n                        \n                        if(x==target.first && y==target.second)\n                            return steps;\n                        \n                        used[x][y] = true;\n                        q.push({x,y});   \n                    }\n                }\n            }\n        }\n        return -1;\n    }\n    \n    int cutOffTree(vector<vector<int>>& forest) {\n        \n        n = forest.size();\n        m = forest[0].size();\n        \n        if(n==0)\n            return -1;\n        \n        typedef tuple<int,int,int> hxy;\n        priority_queue<hxy,vector<hxy>,greater<hxy>> pq;\n       \n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                if(forest[i][j]>1) \n                    pq.push({forest[i][j],i,j});\n            }\n        }\n        \n        int ans = 0;\n        pair<int,int> start{0,0};\n        pair<int,int> target;\n        \n        while(!pq.empty()){\n            auto curr = pq.top();\n            pq.pop();\n            \n            target = {get<1>(curr),get<2>(curr)};\n            int steps = bfs(forest,start,target);\n            \n            if(steps==-1)\n                return -1;\n           \n            ans+=steps;\n            start = target;\n        }\n        \n        \n        return ans;\n    }\n};
['Queue', 'Heap (Priority Queue)']