forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCut Off Trees for Golf Event.cpp
119 lines (79 loc) · 2.48 KB
/
Cut Off Trees for Golf Event.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class Solution {
public:
#define vi vector<int>
#define vvi vector<vi>
vvi forests;
vvi moves;
int R;
int C;
bool isValid(int x,int y){
return x>=0&&x<R&&y>=0&&y<C;
}
int getShortestDistance(int sx,int sy,int ex,int ey){
vvi vis = vvi(R,vi(C,0));
queue<pair<int,int>>Q;
Q.push({sx,sy});
vis[sx][sy] = 1;
int level = 0;
while(!Q.empty()){
queue<pair<int,int>>childQ;
while(!Q.empty()){
auto x = Q.front().first;
auto y = Q.front().second;
Q.pop();
if(x==ex&&y==ey)
return level;
for(auto ele:moves){
int nextX = x+ele[0];
int nextY = y+ele[1];
if(isValid(nextX,nextY)&&!vis[nextX][nextY]&&forests[nextX][nextY]>0){
childQ.push({nextX,nextY});
vis[nextX][nextY]=1;
}
}
}
Q=childQ;
level++;
}
return -1;
}
int cutOffTree(vector<vector<int>>& forest) {
moves={
{0,1},
{1,0},
{0,-1},
{-1,0}
};
forests = forest;
R = forest.size();
C = forest[0].size();
if(forest[0][0]==0)
return -1;
vector<vector<int>>trees;
int i=0;
while(i<R){
int j=0;
while(j<C){
if(forest[i][j]>1)
trees.push_back({forest[i][j],i,j});
j++;
}
i++;
}
if(trees.empty())
return -1;
sort(trees.begin(),trees.end());
int sx = 0;
int sy = 0;
int ans = 0;
for(auto it:trees){
int dis = getShortestDistance(sx,sy,it[1],it[2]);
if(dis==-1)
return -1;
ans+=dis;
sx = it[1];
sy = it[2];
}
return ans;
}
};