Simple BFS | Clean Code | C++
\nclass Solution {\npublic:\n    int cutOffTree(vector<vector<int>>& forest) {\n        if(!forest.size() || !forest[0].size()) return 0;\n        int n = fores
```\nclass Solution {\npublic:\n    int cutOffTree(vector<vector<int>>& forest) {\n        if(!forest.size() || !forest[0].size()) return 0;\n        int n = forest.size();\n        int m = forest[0].size();\n        vector<int> trace;\n        for(int i=0; i<n; i++){\n            for(int j=0; j<m; j++){\n                trace.push_back(forest[i][j]);\n            }\n        }\n        sort(trace.begin(),trace.end());\n        int curI=0,curJ=0;\n        int steps = 0;\n        for(auto i:trace){\n            if(i==0||i==1)  continue;\n            int ans = bfs(curI,curJ,forest,i,n,m);\n            if(ans==-1) return -1;\n            steps+=ans; \n        }\n        return steps;\n    }\nprivate:\n    int bfs(int &curi, int &curj,vector<vector<int>> &forest, int dest,int n, int m){\n        if(forest[curi][curj]==dest)  return 0;\n        vector<vector<int>> visited(n,vector<int>(m,0));\n        visited[curi][curj]=1;\n        list<pair<pair<int,int>,int>> q; //i,j, steps\n        q.push_back({{curi,curj},0});\n        while(!q.empty()){\n            \n            int i = q.front().first.first;\n            int j = q.front().first.second;\n            int steps = q.front().second;\n            q.pop_front();\n            if(forest[i][j]==dest){\n                forest[i][j]=1;\n                curi=i, curj=j;\n                return steps;\n            }\n            if(i+1<n && visited[i+1][j]==0 && forest[i+1][j]!=0){\n                visited[i+1][j]=1;\n                q.push_back({{i+1,j},steps+1});\n            }\n            if(j+1<m && visited[i][j+1]==0 && forest[i][j+1]!=0){\n                visited[i][j+1]=1;\n                q.push_back({{i,j+1},steps+1});\n            }\n            if(i-1>=0 && visited[i-1][j]==0 && forest[i-1][j]!=0){\n                visited[i-1][j]=1;\n                q.push_back({{i-1,j},steps+1});\n            }\n            if(j-1>=0 && visited[i][j-1]==0 && forest[i][j-1]!=0){\n                visited[i][j-1]=1;\n                q.push_back({{i,j-1},steps+1});\n            }\n        }\n        return -1;\n    }\n};\n```
[]