675.Cut Off Trees for Golf Event

You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-negative 2D map, in this map:

  1. 0represents the obstaclecan't be reached.
  2. 1represents the groundcan be walked through.
  3. The place with number bigger than 1represents atreecan be walked through, and this positive number represents the tree's height.

You are asked to cut off all the trees in this forest in the order of tree's height - always cut off the tree with lowest height first. And after cutting, the original place has the tree will become a grass (value 1).

You will start from the point (0, 0) and you should output the minimum steps you need to walk to cut off all the trees. If you can't cut off all the trees, output -1 in that situation.

You are guaranteed that no twotreeshave the same height and there is at least one tree needs to be cut off.

Example 1:

Input:

[
 [1,2,3],
 [0,0,4],
 [7,6,5]
]

Output:
 6

Example 2:

Input:

[
 [1,2,3],
 [0,0,0],
 [7,6,5]
]

Output:
 -1

Example 3:

Input:

[
 [2,3,4],
 [0,0,5],
 [8,7,6]
]

Output:
 6

Explanation:
 You started from the point (0,0) and you can cut off the tree in (0,0) directly without walking.

Hint: size of the given matrix will not exceed 50x50.

Thoughts:

1.BFS

2.A* without heuristics (Dijkstra's Algorithm)

Code (BFS)

class Solution {
    int m, n;
public:
    int cutOffTree(vector<vector<int>>& forest) {
        // find all trees and sort them 
        m = forest.size();
        n = forest[0].size();


        vector<tuple<int, int, int>> trees;
        for ( int y = 0 ; y < m; y++){
            for (int x = 0; x < n; x++){
                if(forest[y][x] > 0){
                    trees.emplace_back(forest[y][x], x, y);
                }
            }
        }
            // sort the trees by height
            sort(trees.begin(), trees.end());

            int sx = 0, sy =0, total_steps = 0;


        // Move from current position to next tree to cut
            for(int i = 0; i < trees.size(); i++){
                int dx = get<1>(trees[i]);
                int dy = get<2>(trees[i]);

            // accumulate pairwise distance using graph search as the answer
                int incr_steps = BFS(forest, sx, sy, dx, dy);
                if (incr_steps == -1) return -1;

                total_steps += incr_steps;

                sx = dx ; 
                sy = dy ; 
            }


        return total_steps;
    }

private :
    int BFS(const vector<vector<int>> & forest,
           int sx, int sy,
           int dx, int dy){

        // left, right, down, up
        static int dir [4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        auto visited = vector<vector<int>>(m, vector<int>(n,0));

        queue <pair<int, int>> q;
        q.emplace(sx, sy);

        int steps = 0;
        while(!q.empty()){
            int cur_nodes = q.size();
            while(cur_nodes--){
                auto node = q.front();
                q.pop();
                int cx = node.first;
                int cy = node.second;

                 // check done 
                if (cx == dx && cy == dy) return steps;

                // move to the next direction
                for ( int i = 0; i < 4; i++){
                    int x = cx + dir[i][0];
                    int y = cy + dir[i][1];

                    if(x < 0 || x == n
                      || y < 0 || y == m
                      || !forest[y][x] 
                      || visited[y][x]
                      ){
                        continue;
                    }

                    // complete
                    visited[y][x] = 1;
                    q.emplace(x,y);
                }
            }
            steps++;
        }

        return -1;
    }


};

Code (Dijkstra's Algorithm)

class Solution:
    def cutOffTree(self, forest):
        """
        :type forest: List[List[int]]
        :rtype: int
        """
        # print (type(forest))
        trees = sorted((v, r, c) for r, row in enumerate(forest)
                       for c, v in enumerate(row) if v > 1)

        sr = sc = ans = 0

        def astar(forest, sr, sc, tr, tc):
            R, C = len(forest), len(forest[0])
            heap = [(0, 0, sr, sc)]
            cost = {(sr, sc): 0}
            while heap:
                f, g, r, c = heapq.heappop(heap)
                if r == tr and c == tc: return g
                for nr, nc in ((r-1,c), (r+1,c), (r,c-1), (r,c+1)):
                    if 0 <= nr < R and 0 <= nc < C and forest[nr][nc]:
                        ncost = g + 1 # + abs(nr - tr) + abs(nc - tc) # heuristic?
                        if ncost < cost.get((nr, nc), 9999):
                            cost[nr, nc] = ncost
                            heapq.heappush(heap, (ncost, g+1, nr, nc))
            return -1

        for _, tr, tc in trees:
            d = astar(forest, sr, sc, tr, tc)
            if d < 0: return -1
            ans += d
            sr, sc = tr, tc
        return an

results matching ""

    No results matching ""