c++ solution using bfs
\nclass Solution {\npublic:\n    int cutOffTree(vector<vector<int>>&mat)\n    {\n        vector<pair<int,int>>d={{-1,0},{1,0},{0,-1},{0,1}};\n        int n=mat.
```\nclass Solution {\npublic:\n    int cutOffTree(vector<vector<int>>&mat)\n    {\n        vector<pair<int,int>>d={{-1,0},{1,0},{0,-1},{0,1}};\n        int n=mat.size();\n        int m=mat[0].size();\n        vector<vector<long long>>v;\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<m;j++)\n            {\n                if(mat[i][j]>1)\n                {\n                    v.push_back({i,j,mat[i][j]});\n                }\n            }\n        }\n        auto bfs=[&](int st1,int st2,int ds1,int ds2)\n        {\n            queue<pair<int,int>>q;\n            q.push({st1,st2});\n            int level=0;\n            vector<vector<bool>>vis(n+2,vector<bool>(m+2,false));\n            vis[st1][st2]=true;\n            while(q.size())\n            {\n                int size=q.size();\n                for(int i=0;i<size;i++)\n                {\n                    auto temp=q.front();\n                    q.pop();\n                    long long x=temp.first;\n                    long long y=temp.second;\n                    if(x==ds1&&y==ds2)\n                    {\n                        return level;\n                    }\n                    for(auto &it:d)\n                    {\n                        long long nx=x+it.first;\n                        long long ny=y+it.second;\n                        if(nx>=0&&ny>=0&&nx<n&&ny<m&&mat[nx][ny]>=1&&vis[nx][ny]==false)\n                        {\n                            q.push({nx,ny});\n                            vis[nx][ny]=true;\n                        }\n                    }\n                }\n                level++;\n            }\n            return -1;\n        };\n        sort(v.begin(),v.end(),[&](auto &v1,auto &v2){return v1[2]<v2[2];});\n        long long st1=0;\n        long long st2=0;\n        long long count=0;\n        for(int i=0;i<v.size();i++)\n        {\n            long long ds1=v[i][0];\n            long long ds2=v[i][1];\n            long long step=bfs(st1,st2,ds1,ds2);\n            if(step<0)\n            {\n                return -1;\n            }\n            count+=step;\n            st1=ds1;\n            st2=ds2;\n        }\n        return count;\n    }\n};\n```
['Breadth-First Search', 'C', 'Sorting', 'C++']