Java BFS ---- Easy to understand
\nclass Solution {\n    int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};\n    public int cutOffTree(List<List<Integer>> forest) {\n        //create a list
```\nclass Solution {\n    int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};\n    public int cutOffTree(List<List<Integer>> forest) {\n        //create a list of int[] {value, x, y}\n        List<int[]> trees = new ArrayList<>();\n        for (int i = 0; i < forest.size(); i++) {\n            for (int j = 0; j < forest.get(0).size(); j++) {\n                int value = forest.get(i).get(j);\n                if (value > 1) trees.add(new int[]{i, j, value});\n            }\n        }\n        \n        Collections.sort(trees, (a, b)->(a[2]-b[2]));\n        int res = 0, x = 0, y = 0;\n        for (int[] tree: trees) {\n            int dist = bfs(forest, x, y, tree[0], tree[1]);\n            if (dist < 0) return -1;\n            else {\n                res += dist;\n                x = tree[0];\n                y = tree[1];\n            }\n        }\n        return res;\n    }\n    private int bfs(List<List<Integer>> forest, int x, int y, int tx, int ty) {\n        int m = forest.size(), n = forest.get(0).size();\n        Queue<int[]> queue = new LinkedList<>();\n        queue.add(new int[]{x, y});\n        boolean[][] visited = new boolean[m][n];\n        visited[x][y] = true;\n        int dist = 0;\n        while (!queue.isEmpty()) {\n            int size = queue.size();\n            for (int j = 0; j < size; j++) {\n                int[] cur = queue.poll();\n                if (cur[0] == tx && cur[1] == ty) return dist;\n                for (int i = 0; i < 4; i++) {\n                    int nx = cur[0]+dirs[i][0];\n                    int ny = cur[1]+dirs[i][1];\n                    if (nx < 0 || nx >= m || ny < 0 || ny >= n || \n                        visited[nx][ny] || forest.get(nx).get(ny) <= 0) continue;\n                    visited[nx][ny] = true;\n                    queue.add(new int[]{nx, ny});\n                }\n            }\n            dist++;\n        }\n        return -1;\n    }\n}\n```
[]