Very Clean JAVA BFS Solution .
BFS is used to find shortest path between src and destination, and PriorityQueue is used to find destinations..\n\'\'\'\n    public int cutOffTree(List> forest)
BFS is used to find shortest path between src and destination, and PriorityQueue is used to find destinations..\n\'\'\'\n    public int cutOffTree(List<List<Integer>> forest) {\n        \n       int n = forest.size();\n       int m = forest.get(0).size();\n       int dir[][]= {{1,0},{0,1},{-1,0},{0,-1}}; \n       \n       PriorityQueue<Integer> minheap =new PriorityQueue<>(); \n        \n       for(List<Integer> al  : forest)  for(int val : al) if(val>1)  minheap.add(val);\n       \n       int result=0;\n       int [] src={0,0}; \n        \n        while(minheap.size()>0)\n        {\n            boolean vis [][] =new boolean[n][m];\n            \n            Queue<int[]> q =new LinkedList<>();\n              \n            q.add(new int[]{src[0],src[1],0});\n            int target = minheap.remove(),ans=-1;    \n      \n            while(!q.isEmpty())\n            {\n               int a [] = q.remove();    \n                \n               if(vis[a[0]][a[1]]) continue; \n               vis[a[0]][a[1]] =true;\n                \n               //check for target\n                if(forest.get(a[0]).get(a[1])==target) \n                {\n                  src[0]=a[0];   \n                  src[1]=a[1];\n                  ans = a[2];  \n                  break;    \n                }\n                \n               for(int b[] : dir)\n               {\n                   int r=a[0]+b[0];\n                   int c =a[1]+b[1];\n                   \n                   if(r<0 || r>=n || c<0 || c>=m || vis[r][c] || forest.get(r).get(c)==0) continue;\n                   \n                     q.add(new int[]{r,c,a[2]+1});\n               } \n                \n            }\n            \n            if(ans==-1) return -1;\n            \n            result+=ans; \n        }\n   \n        return result;\n    }\n\'\'\'
[]