/*
1. build priority queue by the weight of the trees
2. start from 0,0 to the lowest tree, and the compute the minSteps of this tree.从最小的树开始。
3. change the start to the lowest tree and cut the second lowest tree. 从次小的开始。
4. BFS 找出从当前位置到目标树的最短距离。
*/
typedef struct position position_t;
struct position
{
int row;
int col;
int height;
position(int r, int c, int h):row(r),col(c),height(h){};
};
auto tree_compare = [](position_t firstTree, position_t secondTree){
return firstTree.height > secondTree.height;
};
class Solution {
private:
vector
int minSteps(position_t& start, position_t& end, vector
{
if(0 == start.height) return -1;
int rows = forest.size();
int cols = forest[0].size();
vector
seen[start.row][start.col] = true;
queue
q.push(start);
int step = 0;
while(!q.empty())
{
int sizeOneLayer = q.size();
for(int i = 0; i
{
position_t curPos = q.front(); q.pop();
if(curPos.row == end.row && curPos.col == end.col) return step;
for(auto direct:directs)
{
//int newRow = start.row + direct[0]; // should be curPos, not start......!!!!!
int newRow = curPos.row + direct[0];
//int newCol = start.col + direct[1];
int newCol = curPos.col + direct[1]; // should be curPos, not start......!!!!!
if(newRow <0 || newRow >=rows
|| newCol <0 || newCol >=cols
//|| forest[newRow][newCol]<1
|| forest[newRow][newCol]==0
|| seen[newRow][newCol]
) continue;
else
{
q.push(position_t(newRow,newCol,forest[newRow][newCol]));
seen[newRow][newCol] = true;
}
}
//++step;
}
++step;
}
return -1;
//...
}
public:
int cutOffTree(vector
if(forest.size() == 0) return 0;
// build priority queue by the weight of the trees
priority_queue
int rows = forest.size();
int cols = forest[0].size();
for(int i = 0; i
for(int j = 0;j
{
if(forest[i][j] > 1) pq.push(position_t(i,j,forest[i][j]));
};
int ans = 0;
position_t start(0,0,forest[0][0]);
// start from 0,0 to the lowest tree, and the compute the minSteps of this tree.
while(!pq.empty())
{
position_t target = pq.top(); pq.pop();
int step = 0;
step = minSteps(start,target,forest);
if(step == -1) return -1;
ans += step;
// change the start to the lowest tree and cut the second lowest tree
start = target;
}
return ans;
}
};
void main()
{
// [[54581641,64080174,24346381,69107959],[86374198,61363882,68783324,79706116],[668150,92178815,89819108,94701471],[83920491,22724204,46281641,47531096],[89078499,18904913,25462145,60813308]]
//vector
vector
Solution().cutOffTree(forest);
}
/*
others code for java.
Since we have to cut trees in order of their height, we first put trees (int[] {row, col, height}) into a priority queue and sort by height.