C++ solution using a* search
\nclass Solution {\n\tint find(vector<vector<int>> &forest, int cur, int tar) {\n\t\tint n = forest[0].size(), m = forest.size();\n\t\tint tr = tar/n, tc = tar%
```\nclass Solution {\n\tint find(vector<vector<int>> &forest, int cur, int tar) {\n\t\tint n = forest[0].size(), m = forest.size();\n\t\tint tr = tar/n, tc = tar%n, curr = cur/n, curc = cur%n;\n\t\tauto cmp = [](const pair<int,int> &a, const pair<int,int> &b) {\n\t\t\treturn a.second > b.second;\n\t\t};\n\t\tpriority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> q{cmp};\n\t    unordered_set<int> vis;\n\t    q.push(make_pair(cur, abs(tr-curr)+abs(tc-curc)));\n\t    while (!q.empty()) {\n\t    \tauto f = q.top();\n\t    \tq.pop();\n\t\t\tif (vis.count(f.first)) continue;\n\t\t\tvis.insert(f.first);\n\t    \tif (f.first == tar) return f.second;\n\t    \tint dirs[][2] = {{1,0},{-1,0},{0,1},{0,-1}};\n\t    \tint r = f.first/n, c = f.first%n;\n\t    \tfor (auto &dir : dirs) {\n\t    \t\tint newr = r + dir[0], newc = c + dir[1];\n\t    \t\tif (newr < 0 || newr >= m || newc < 0 || newc >= n || \n\t    \t\t\tforest[newr][newc] == 0 || vis.count(newr*n+newc)) continue;\n\t    \t\tq.push(make_pair(newr*n+newc, f.second-abs(r-tr)-abs(c-tc)+1+abs(newr-tr)+abs(newc-tc)));\n\t    \t}\n\t    }\n\t    return -1;\n\t}\npublic:\n    int cutOffTree(vector<vector<int>>& forest) {\n        if (forest.size() == 0 || forest[0].size() == 0) return 0;\n        int m = forest.size(), n = forest[0].size();\n        vector<int> targets;\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (forest[i][j] > 1) targets.push_back(i*n+j);\n            }\n        }\n        sort(targets.begin(), targets.end(), [&forest,n](int a, int b) {\n            return forest[a/n][a%n] < forest[b/n][b%n];\n        });\n        int ans = 0, cur = 0;\n        for (auto tar : targets) {\n            auto dis = find(forest, cur, tar);\n            if (dis == -1) return -1;\n            ans += dis;\n            cur = tar;\n        }\n        return ans;\n    }\n};\n```\nbfs is too slow to passing the test cases
[]