BFS C++
\nclass Solution {\npublic:\n    int cutOffTree(vector<vector<int>>& f) {\n        vector<int> trees;\n        for (auto& v : f) {\n            for (int x : v) 
```\nclass Solution {\npublic:\n    int cutOffTree(vector<vector<int>>& f) {\n        vector<int> trees;\n        for (auto& v : f) {\n            for (int x : v) {\n                if (x > 1)\n                    trees.push_back(x);\n            }\n        }\n        sort(trees.begin(), trees.end());\n        int treecounter = 0;\n        int visited[51][51] = { 0 };\n        queue<tuple<int, int, int>> q;\n        q.push({0, 0, trees[0]});\n        vector<vector<int>> dirs = {{-1 , 0}, {0, -1}, {1, 0}, {0, 1}};\n        int steps = 0;\n        while (q.size()) {\n            int size = q.size();\n            while (size--) {\n                auto[x, y, t] = q.front();\n                q.pop();\n                // Discontinue this search as the corresponding\n                // tree is no more\n                if (trees[treecounter] != t)\n                    continue;\n                // Found tree; cut tree\n                if (f[x][y] == t) {\n                    f[x][y] = 1;\n                    treecounter++;\n                    if (treecounter == trees.size())\n                        return steps;\n                    // Next tree to target\n                    t = trees[treecounter];\n                }\n                for (auto& d : dirs) {\n                    int nx = x + d[0];\n                    int ny = y + d[1];\n                    if (nx < 0 || ny < 0 || nx == f.size() || ny == f[0].size())\n                        continue;\n                    if (f[nx][ny] == 0)\n                        continue;\n                    // If we\'ve been here before looking for the same tree\n                    if (visited[nx][ny] == t)\n                        continue;\n                    visited[nx][ny] = t;\n                    q.push({nx, ny, t});\n                }\n            }\n            steps++;\n        }\n        return -1;\n    }\n};\n```
[]