C++ with Priority Queue and BFS
put the tree positions into a set(remeber no two trees can have the same height?). this set will act as a priority queue.\n2. iterate the set and at every posit
1. put the tree positions into a set(remeber no two trees can have the **same** height?). this set will act as a priority queue.\n2. iterate the set and at every position run a BFS, placing the tree position as the destination.\n\t1. if the BFS  returns -1, there is no way we can cut off all the trees. return -1.\n\t2. else add the distnace to the answer.\n\nhere is the code:\n```\nclass Solution {\nprivate:\n    const int INF = 1061109567;\npublic:\n    int cutOffTree(vector<vector<int>>& forest) {\n        int n = forest.size() ;\n        int m = forest[0].size() ;\n        \n        int ans = 0 ;\n        \n        set<pair<int,pair<int,int>>> points ;\n        \n        for(int i = 0; i<n ; i++){\n            for(int j = 0; j<m; j++){\n                if(forest[i][j]>1){\n                    points.insert({forest[i][j], {i,j}}) ;\n                }\n            }\n        }\n\t\t\n        int sx = 0, sy = 0 ;\n        for(auto elem :points){\n            int dx = elem.second.first ;\n            int dy = elem.second.second ;\n            int bfs_dist = bfs(forest, n, m, sx, sy, dx, dy) ;\n            if(bfs_dist == -1) return -1 ;\n            ans+=bfs_dist ;\n            forest[dx][dy] = 1;\n            sx = dx ;\n            sy = dy ;   \n        }\n\t\t\n        return ans ;    \n    }\n    \n    int bfs(vector<vector<int>> &forest, int n, int m , int sx, int sy, int dx, int dy){\n        int distance[n+2][m+2] ;\n        memset(distance, 0x3f, sizeof(distance));\n        int dirx[] = {1, 0, -1, 0} ;\n        int diry[] = {0, 1,0, -1} ;\n        \n        queue<pair<int,int>> q;\n        q.push({sx,sy}) ;\n        distance[sx][sy] = 0 ;\n        \n        while(!q.empty()){\n            pair<int,int> p = q.front() ;\n            q.pop() ;\n            if(p.first == dx && p.second == dy) return distance[dx][dy] ;\n            \n            for(int i = 0 ;i<4 ;i++){\n                int x = p.first + dirx[i] ;\n                int y = p.second + diry[i] ;\n                \n                if(x<0 || x>=n || y <0 || y>=m)continue ;\n                if(forest[x][y] == 0)continue ;\n                if(distance[x][y] != INF)continue ;\n                distance[x][y] = distance[p.first][p.second] + 1 ;\n                q.push({x,y}) ;\n            }   \n            \n        }\n        \n        return -1 ;     \n    } \n};\n```
['Breadth-First Search', 'Heap (Priority Queue)', 'C++']