[C++] | Simple BFS
\nclass Solution {\npublic:\n    map<int, int> hash;\n    vector<int> DIR = {1, 0, -1, 0, 1};\n    int n, m;\n    int cutOffTree(vector<vector<int>>& f) {\n    
```\nclass Solution {\npublic:\n    map<int, int> hash;\n    vector<int> DIR = {1, 0, -1, 0, 1};\n    int n, m;\n    int cutOffTree(vector<vector<int>>& f) {\n        n = f.size(), m = f[0].size();\n        int cur = 0, result = 0;\n        for(int i = 0; i < n; i++)\n            for(int j = 0; j < m; j++)\n                if(f[i][j] > 1)\n                    hash[f[i][j]] = i * m + j;\n        \n        for(auto& a: hash){\n            int steps = helper(f, cur, a.second);\n            if(steps == -1e9) return -1;\n            result += steps;\n            cur = a.second;\n        }\n        return result;\n    }\n    \n    int helper(vector<vector<int>>& f, int cur, int target){\n        queue<int> q;\n        int steps = 0;\n        q.push({cur});\n        vector<vector<bool>> vis(n, vector<bool>(m));\n        while(!q.empty()){\n            int sz = q.size();\n            while(sz--){\n                int pos = q.front(), r = pos / m, c = pos % m;\n                q.pop();\n                if(pos == target)\n                    return steps;\n                for(int k = 0; k < 4; k++){\n                    int nr = r + DIR[k], nc = c + DIR[k + 1];\n                    if(nr < 0 || nr == n || nc < 0 || nc == m || vis[nr][nc] || !f[nr][nc])\n                        continue;\n                    q.push({nr * m + nc});\n                    vis[nr][nc] = true;\n                }\n            }\n            steps++;\n        }\n        return -1e9;\n    }\n};\n```
['Breadth-First Search', 'C', 'C++']