PQ + BFS (easy explanation)
To cut the shortest trees first - \n- add all the tree with their position in a priority queue (min heap).\n\nTo find the min no. of steps to cut all trees star
To cut the shortest trees first - \n- add all the tree with their position in a priority queue (min heap).\n\nTo find the min no. of steps to cut all trees starting from (0,0)\n- Set the src to (0,0)\n- Get position of shortest height tree, let\'s say (x,y)\n- BFS to find min steps to reach from (0,0) to (x,y)\n- update src to (x,y) and repeat steps for the next shortest tree\n\n```\nclass Solution {\n    private static final int[][] DIR = new int[][]{{1,0}, {-1,0}, {0,1}, {0,-1}};\n    \n    public int cutOffTree(List<List<Integer>> forest) {\n        int m = forest.size(), n = forest.get(0).size();\n        // [tree height, row, col]\n        PriorityQueue<int[]> trees = new PriorityQueue<int[]>(\n            (a,b) -> Integer.compare(a[0], b[0]));\n        \n        for(int i=0; i<m; i++) \n            for(int j=0; j<n; j++) {\n                int ht = forest.get(i).get(j);\n                if( ht > 1 )\n                    trees.offer(new int[]{ht, i, j});\n            }\n        \n        int ans = 0;\n        int currX = 0, currY = 0;\n        \n        while( !trees.isEmpty() ) {\n            int i = trees.peek()[1], j = trees.poll()[2];\n            \n            int steps = bfs(currX, currY, i, j, forest);\n            if( steps == -1 )\n                return -1;\n            ans += steps;\n            currX = i;\n            currY = j;\n        }\n        return ans;\n    }\n    \n    private int bfs(int srcRow, int srcCol, int destRow, int destCol, List<List<Integer>> forest) {\n        int m = forest.size(), n = forest.get(0).size();\n        boolean[][] visited = new boolean[m][n];\n        Queue<int[]> queue = new LinkedList();\n        int steps = 0;\n\n        queue.offer(new int[]{ srcRow, srcCol });\n        visited[srcRow][srcCol] = true;\n        \n        while( !queue.isEmpty() ) {\n            int size = queue.size();\n            \n            while( size-- > 0 ) {\n                int i = queue.peek()[0];\n                int j = queue.peek()[1];\n                queue.poll();\n                \n                if( i == destRow && j == destCol )\n                    return steps;\n                \n                for(int[] dir : DIR) {\n                    int di = i + dir[0];\n                    int dj = j + dir[1];\n\n                    if( di < 0 || dj < 0 || di == m || dj == n )\n                        continue;\n                    \n                    if( visited[di][dj] || forest.get(di).get(dj) == 0 ) \n                        continue;\n                    \n                    queue.offer(new int[]{di, dj});\n                    visited[di][dj] = true;\n                }\n            }\n            steps++;\n        }\n        return -1;\n    }\n}\n```
['Java']