<p>You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an <code>m x n</code> matrix. In this matrix:</p>

<ul>
	<li><code>0</code> means the cell cannot be walked through.</li>
	<li><code>1</code> represents an empty cell that can be walked through.</li>
	<li>A number greater than <code>1</code> represents a tree in a cell that can be walked through, and this number is the tree&#39;s height.</li>
</ul>

<p>In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.</p>

<p>You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes <code>1</code> (an empty cell).</p>

<p>Starting from the point <code>(0, 0)</code>, return <em>the minimum steps you need to walk to cut off all the trees</em>. If you cannot cut off all the trees, return <code>-1</code>.</p>

<p><strong>Note:</strong> The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/trees1.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]
<strong>Output:</strong> 6
<strong>Explanation:</strong> Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/trees2.jpg" style="width: 242px; height: 242px;" />
<pre>
<strong>Input:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The trees in the bottom row cannot be accessed as the middle row is blocked.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]
<strong>Output:</strong> 6
<b>Explanation:</b> You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == forest.length</code></li>
	<li><code>n == forest[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 50</code></li>
	<li><code>0 &lt;= forest[i][j] &lt;= 10<sup>9</sup></code></li>
	<li>Heights of all trees are <strong>distinct</strong>.</li>
</ul>

class Solution {
    static constexpr int DIR[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
    struct Cell {
        short r : 8;
        short c : 8;
    };
    int doit(const vector<vector<int>>& forest, Cell start, vector<int> &curr, vector<int> &prev, vector<Cell> &bfs) {
        const int M = forest.size(), N = forest[0].size();
        int steps = 0;
        swap(curr, prev);
        fill(begin(curr), end(curr), -1);
        curr[start.r * N + start.c] = steps;
        if (prev[start.r * N + start.c] != -1) {
            return prev[start.r * N + start.c];
        }
        bfs.clear();
        bfs.push_back(start);
        while (!bfs.empty()) {
            int size = bfs.size();
            steps++;
            while (size--) {
                auto [r0, c0] = bfs[size];
                swap(bfs[size], bfs.back());
                bfs.pop_back();
                for (auto [dr, dc] : DIR) {
                    short r1 = r0 + dr, c1 = c0 + dc;
                    int pos = r1 * N + c1;
                    if (r1 >= 0 && r1 < M && c1 >= 0 && c1 < N && forest[r1][c1] > 0 && curr[pos] == -1) {
                        if (prev[pos] != -1) {
                            return steps + prev[pos];
                        }
                        curr[pos] = steps;
                        bfs.push_back({r1, c1});
                    }
                }
            }
        }
        return -1;
    }
    int manhattan_distance(vector<Cell> &cells) {
        int result = 0;
        Cell prev{0, 0};
        for (auto &cell : cells) {
            result += abs(prev.r - cell.r) + abs(prev.c - cell.c);
            prev = cell;
        }
        return result;
    }
public:
    int cutOffTree(vector<vector<int>>& forest) {
        const int M = forest.size(), N = forest[0].size();
        if (forest[0][0] == 0) {
            return -1;
        }
        int obstacles = 0;
        vector<Cell> cells;
        cells.reserve(8);

        for (short r = 0; r < M; r++) {
            for (short c = 0; c < N; c++) {
                if (forest[r][c] > 1) {
                    cells.push_back({r, c});
                } else if (forest[r][c] == 0) {
                    obstacles++;
                }
            }
        }
        sort(begin(cells), end(cells), [&forest](const Cell &a, const Cell &b){
            return forest[a.r][a.c] < forest[b.r][b.c];
        });
        if (obstacles == 0) {
            return manhattan_distance(cells);
        }
        vector<int> curr(M * N, -1), prev = curr;
        curr[0] = 0;

        vector<Cell> bfs;
        bfs.reserve(8);

        int steps = 0;

        for (auto &cell : cells) {
            int result = doit(forest, cell, curr, prev, bfs);

            if (result != -1) {
                steps += result;
            } else {
                return -1;
            }
        }
        return steps;
    }
};
15185