11
bool isValid(int x, int y) {12
return x >= 0 && x < R && y >= 0 && y < C;15
int getShortestDistance(int sx, int sy, int ex, int ey) {16
vvi vis = vvi(R, vi(C, 0));17
queue<pair<int, int>> Q;25
queue<pair<int, int>> childQ;28
auto x = Q.front().first;29
auto y = Q.front().second;33
if (x == ex && y == ey) return level;35
for (auto ele : moves) {36
int nextX = x + ele[0];37
int nextY = y + ele[1];39
if (isValid(nextX, nextY) && !vis[nextX][nextY] && forests[nextX][nextY] > 0) {40
childQ.push({nextX, nextY});41
vis[nextX][nextY] = 1;53
int cutOffTree(vector<vector<int>> &forest) {54
moves = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};61
if (forest[0][0] == 0) return -1;63
vector<vector<int>> trees;69
if (forest[i][j] > 1) trees.push_back({forest[i][j], i, j});76
if (trees.empty()) return -1;78
sort(trees.begin(), trees.end());85
for (auto it : trees) {86
int dis = getShortestDistance(sx, sy, it[1], it[2]);88
if (dis == -1) return -1;