forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path675.Cut-Off-Trees-for-Golf-Event.cpp
75 lines (63 loc) · 1.94 KB
/
675.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
class Solution {
public:
int cutOffTree(vector<vector<int>>& forest)
{
map<int,pair<int,int>>Map;
int M=forest.size();
int N=forest[0].size();
for (int i=0; i<M; i++)
for (int j=0; j<N; j++)
{
if (forest[i][j]>1)
Map[forest[i][j]]={i,j};
}
int x=0;
int y=0;
int result=0;
for (auto a:Map)
{
int m=a.second.first;
int n=a.second.second;
int step=Go(x,y,m,n,forest);
if (step==-1) return -1;
else result+=step;
x=m;
y=n;
}
return result;
}
int Go(int x0, int y0, int m, int n, vector<vector<int>>& forest)
{
vector<pair<int,int>>dir={{0,1},{0,-1},{1,0},{-1,0}};
int M=forest.size();
int N=forest[0].size();
auto visited=vector<vector<int>>(M,vector<int>(N,0));
queue<pair<int,int>>q;
q.push({x0,y0});
visited[x0][y0]=1;
int count=-1;
while (!q.empty())
{
int num=q.size();
count++;
for (int i=0; i<num; i++)
{
int x=q.front().first;
int y=q.front().second;
q.pop();
if (x==m && y==n) return count;
for (int k=0; k<4; k++)
{
int a=x+dir[k].first;
int b=y+dir[k].second;
if (a<0 || a>=M || b<0 || b>=N) continue;
if (forest[a][b]==0) continue;
if (visited[a][b]==1) continue;
q.push({a,b});
visited[a][b]=1;
}
}
}
return -1;
}
};