C++ || Clean and Simple || BFS || With Proper Comments
\nclass Solution {\npublic:\n    int sx=0,sy=0;\n    vector<vector<int>> offsets={{1,0},{0,1},{-1,0},{0,-1}};\n    int cutOffTree(vector<vector<int>>& forest) {
```\nclass Solution {\npublic:\n    int sx=0,sy=0;\n    vector<vector<int>> offsets={{1,0},{0,1},{-1,0},{0,-1}};\n    int cutOffTree(vector<vector<int>>& forest) {\n        \n        if(forest[0][0]==0)\n            return -1;\n        \n        //first get heights of all the trees.\n        vector<int> tree_heights;\n        for(int i=0;i<forest.size();i++){\n            for(int j=0;j<forest.at(0).size();j++){\n                if(forest[i][j]!=1&&forest[i][j]!=0)\n                    tree_heights.push_back(forest[i][j]);\n            }\n        }\n        \n        //sort them (smaller to larger)\n        sort(tree_heights.begin(),tree_heights.end());\n        vector<vector<int>> temp;\n        \n        int total_steps=0,target;\n        //loop that will find the next tree which we have to cut. and after finding that tree\n        // we add the distance to total_distance and change the next tree(target) and update the forest vector\n        for(int i=0;i<tree_heights.size();i++){\n\t\t\n            target=tree_heights[i];\n            temp=forest;\n            int h=find_tree(sx,sy,target,temp);\n            if(h==-1){\n                return -1;\n            }\n        \n\t\t    total_steps+=h;\n            forest[sx][sy]=1;\n        }\n        return total_steps;\n    }\n    \n    \n    //this function finds tree with a given height from a starting point.\n\t//function itself is pretty standard BFS implementation.\n    int find_tree(int xi,int yi,int target,vector<vector<int>>&temp){\n        \n\t\t//corner case\n        if(temp[xi][yi]==target){\n            sx=xi;\n            sy=yi;\n            return 0;\n        }\n        \n        queue<pair<int,int>> q;\n        q.push({xi,yi});\n        \n        int current_steps=1;\n        \n        while(!q.empty()){\n            int l=q.size();\n            for(int z=0;z<l;z++){\n                auto[i,j]=q.front();\n                q.pop();\n                \n                for(int m=0;m<4;m++){\n                    \n                    int x=i-offsets[m][0];\n                    int y=j-offsets[m][1];\n                    \n                    if(x<0||y<0||x>=temp.size()||y>=temp.at(0).size()||temp[x][y]==0||temp[x][y]==-1)\n                        continue;\n                    \n                    if(temp[x][y]==target){\n                        sx=x;\n                        sy=y;\n                        return current_steps;\n                    }\n                    \n                    temp[x][y]=-1;\n                    q.push({x,y});\n                }\n            }\n            current_steps++;\n        }\n        return -1;\n    }    \n};\n```
[]