Java BFS + PriorityQueue + clean code
\nclass Solution {\n    public int cutOffTree(List<List<Integer>> forest) {\n        // if(forest.get(0).get(0) == 0)\n        //     return -1;\n        \n    
```\nclass Solution {\n    public int cutOffTree(List<List<Integer>> forest) {\n        // if(forest.get(0).get(0) == 0)\n        //     return -1;\n        \n        int m = forest.size(), n = forest.get(0).size();\n        int ans = 0, steps = 0;\n        \n        PriorityQueue<Integer> pq = new PriorityQueue<>();\n        Queue<int[]> q = new LinkedList<>();\n        boolean vis[][] = new boolean[m][n];\n        \n        int []dx = {0, 0, -1, 1};\n        int []dy = {1, -1, 0, 0};\n        \n        for(int i=0; i<m; i++)\n            for(int j=0; j<n; j++)\n                if(forest.get(i).get(j) > 1)\n                    pq.offer(forest.get(i).get(j));\n        \n        q.add(new int[]{0, 0});\n        vis[0][0] = true;\n        \n        \n        while(!q.isEmpty()) {\n            int sz = q.size();\n            \n            for(int c=0; c<sz; c++) {\n                int x = q.peek()[0], y = q.peek()[1];\n                q.remove();\n                \n                // System.out.println(x + " " + y);\n                if(forest.get(x).get(y) == pq.peek()) {\n                    pq.poll();\n                    forest.get(x).set(y, 1);\n                    ans += steps;\n                    if(pq.size() == 0)\n                        return ans;\n                    vis = new boolean[m][n];\n                    vis[x][y] = true;\n                    q.clear();\n                    steps = -1;\n                    q.add(new int[]{x, y});\n                    break;\n                }\n                \n                for(int i=0; i<4; i++) {\n                    int nx = x + dx[i], ny = y + dy[i];\n                    \n                    if(nx < 0 || ny < 0 || nx >= m || ny >= n || forest.get(nx).get(ny) == 0 || vis[nx][ny]) {\n                        continue;\n                    }\n                    q.add(new int[]{nx, ny});\n                    vis[nx][ny] = true;\n                }\n            }\n            \n           steps++;\n        }\n        \n        return -1;\n    }\n}\n```
[]