C++ | BFS+sort
\nclass Solution {\npublic:\n    int dx[4]={1,0,0,-1};\n    int dy[4]={0,1,-1,0};\n    int m,n;\n    bool isvalid(int i,int j)\n    {\n        if(i<0 || j<0 || 
```\nclass Solution {\npublic:\n    int dx[4]={1,0,0,-1};\n    int dy[4]={0,1,-1,0};\n    int m,n;\n    bool isvalid(int i,int j)\n    {\n        if(i<0 || j<0 || i>=m || j>=n)\n            return false;\n        return true;\n    }\n    int BFS(int si,int sj,int di,int dj,vector<vector<int>>forest)\n    {\n        queue<pair<int,int>>q;\n        q.push({si,sj});\n        forest[si][sj]=0;\n        int res=0;\n        while(!q.empty())\n        {\n            int n=q.size();\n            while(n--)\n            {\n                int i=q.front().first,j=q.front().second;\n                q.pop();\n                if(i==di && j==dj)\n                    return res;\n                for(int k=0;k<4;k++)\n                {\n                    int x=i+dx[k],y=j+dy[k];\n                    if(isvalid(x,y) && forest[x][y]!=0)\n                    {\n                        forest[x][y]=0;\n                        q.push({x,y});\n                    }\n                }\n            }\n            res++;\n        }\n        return -1;\n    }\n    int cutOffTree(vector<vector<int>>& forest) \n    {\n        vector<vector<int>>v;\n        m=forest.size(),n=forest[0].size();\n        for(int i=0;i<m;i++)\n        {\n            for(int j=0;j<n;j++)\n            {\n                if(forest[i][j]>1)\n                    v.push_back({forest[i][j],i,j});\n            }\n        }\n        sort(v.begin(),v.end());\n        int i=0,j=0,res=0;\n        for(auto p:v)\n        {\n            int dist=BFS(i,j,p[1],p[2],forest);\n            if(dist==-1)\n                return -1;\n            res+=dist;\n            i=p[1],j=p[2];\n        }\n        return res;\n    }\n};\n```
[]