Use BFS and Sorting
\n       int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};\n        int solve(int s,int e,int x,int y,vector>& forest){\n        if(s==x && e==y) return 0;\n        \n
\n       int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};\n        int solve(int s,int e,int x,int y,vector<vector<int>>& forest){\n        if(s==x && e==y) return 0;\n        \n        int n=forest.size();\n        int m=forest[0].size();\n        queue<pair<int,int>> q;\n        int vis[n][m];\n        memset(vis,0,sizeof(vis));\n        \n        vis[s][e]=1;\n        q.push({s,e});\n        int count=0;\n        while(!q.empty()){\n            count++;\n            int nn=q.size();\n            while(nn--){\n                auto it=q.front();\n                q.pop();\n                \n                for(int i=0;i<4;i++){\n                    int n_x=it.first+dir[i][0];\n                    int n_y=it.second+dir[i][1];\n                    if(n_x<0 || n_y<0 || n_x>=n || n_y>=m || vis[n_x][n_y]==1 || forest[n_x][n_y]==0){\n                        continue;\n                    }\n                    q.push({n_x,n_y});\n                    vis[n_x][n_y]=1;\n                    if(n_x==x && n_y==y) return count;\n                   \n                }\n            }\n        }\n        return -1;\n    }\n    \n    int cutOffTree(vector<vector<int>>& forest) {\n        \n        for(int i=0;i<forest.size();i++){\n            for(int j=0;j<forest[i].size();j++){\n                if(forest[i][j]>1){\n                    ans.push_back({forest[i][j],i,j});\n                }\n            }\n        }\n        sort(ans.begin(),ans.end());\n        int s=0,e=0;\n        int res=0;\n        for(auto &it:ans){\n            int d=solve(s,e,it[1],it[2],forest);\n            if(d==-1){\n                return -1;\n            }\n            res+=d;\n            s=it[1];\n            e=it[2];\n        }\n        return res;\n        \n    }
['Breadth-First Search']