C++ Sorting + BFS Solution
cpp\ntypedef vector<vector<int>> vvi; \ntypedef vector<vector<bool>> vvb; \nclass Solution {\npublic:\n    bool isValid(int x, int y, int n, int m){\n        re
```cpp\ntypedef vector<vector<int>> vvi; \ntypedef vector<vector<bool>> vvb; \nclass Solution {\npublic:\n    bool isValid(int x, int y, int n, int m){\n        return x>=0 && y>=0 && x<n && y<m; \n    }\n    // The function gives the length of shortest path\n    // from (x1,y1)->(x2,y2)\n    int bfs(int x1, int y1, int x2,int y2, vvi &forest){\n        int n = forest.size(), m = forest[0].size(); \n        int dx[4] = {1,-1,0,0};\n        int dy[4] = {0,0,1,-1}; \n        vector<vector<bool>> vis(n, vector<bool>(m, false)); \n        queue<pair<int, int>> q;\n        q.push({x1, y1}); \n        vis[x1][y1] = true;\n        int cnt = 0; \n        // Level Order Traversal\n        while(!q.empty()){\n            int sz = q.size(); \n            while(sz--){\n                auto node = q.front(); q.pop(); \n                int x = node.first, y = node.second; \n                if(x == x2 && y==y2)\n                    return cnt; \n                for(int i = 0; i<4; ++i){\n                    int xr = x + dx[i], yr = y + dy[i]; \n                    if(isValid(xr,yr,n,m) && !vis[xr][yr]){\n                        if(forest[xr][yr] > 0){\n                            q.push({xr,yr});\n                            vis[xr][yr] = true; \n                        }\n                    }\n                }\n            }\n            cnt++; \n        }\n        return -1; \n    }\n    int cutOffTree(vector<vector<int>>& forest) {\n        if(forest[0][0] == 0)\n            return -1; \n        int n = forest.size(), m = forest[0].size(); \n        // Collect the trees with coordinates in heightwise order\n        vector<pair<int, pair<int, int>>> trees; \n        for(int i = 0; i<n; ++i){\n            for(int j = 0; j<m; ++j){\n                if(forest[i][j] > 1){\n                    trees.push_back({forest[i][j], {i,j}}); \n                }\n            }\n        }\n        sort(trees.begin(), trees.end()); \n        if(trees[0].second.first != 0 || trees[0].second.second != 0)\n            trees.insert(trees.begin(), {0,{0,0}});\n        // Traverse the order and find the shortest path between two adj trees\n        int steps = 0; \n        for(int i = 1; i<trees.size(); ++i){\n            auto src = trees[i-1].second; \n            auto dest = trees[i].second; \n            int x1 = src.first, y1 = src.second; \n            int x2 = dest.first, y2 = dest.second; \n            int cnt = bfs(x1, y1, x2, y2, forest); \n            if(cnt == -1)\n                return -1; \n            steps += cnt; \n        }\n        return steps; \n    }\n};\n```
['Breadth-First Search', 'Graph', 'C', 'Sorting', 'C++']