题意
给你一个二维矩阵表示森林,为0的地方不可行,大于1的地方表示树,值的大小就是树的高度,所有大于等于1的地方是可以走的,现在你从 (0,0) ( 0 , 0 ) 开始,按树的高度从小到大遍历所有的树,问最短路径。
题解
存下所有树的坐标,按树的高度从小大大依次用bfs求最短路径就好了。
代码
struct Node {
int x, y, step;
int h;
bool operator==(const Node &b) const {
return x == b.x && y == b.y;
}
bool operator<(const Node &b) const {
return h < b.h;
}
};
int moves[][2] = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
class Solution {
public:
int cutOffTree(vector<vector<int>>& forest) {
if (forest[0][0] == 0) {
return -1;
}
vector<Node> v;
for (int i = 0; i < forest.size(); i++) {
for (int j = 0; j < forest[0].size(); j++) {
if (forest[i][j] > 1) {
Node temp;
temp.x = i;
temp.y = j;
temp.step = 0;
temp.h = forest[i][j];
v.push_back(temp);
}
}
}
Node temp;
temp.x = 0;
temp.y = 0;
temp.step = 0;
temp.h = 0;
v.push_back(temp);
sort(v.begin(), v.end());
int ans = 0;
for (int i = 0; i < v.size() - 1; i++) {
int temp = bfs(v[i], v[i + 1], forest);
if (temp == -1) {
return -1;
}else{
ans += temp;
}
}
return ans;
}
int bfs(Node st, Node ed, vector<vector<int>>& forest) {
st.step = 0;
queue<Node> q;
q.push(st);
int mark[51][51];
memset(mark, 0, sizeof(mark));
mark[st.x][st.y] = 1;
while (!q.empty()) {
Node n = q.front();
q.pop();
if (n == ed) {
return n.step;
}
for (int i = 0; i < 4; i++) {
Node temp = n;
temp.step++;
temp.x += moves[i][0];
temp.y += moves[i][1];
if (temp.x < 0 || temp.x >= forest.size() || temp.y < 0 || temp.y >= forest[0].size()) {
continue;
}
if (mark[temp.x][temp.y]) {
continue;
}
if (forest[temp.x][temp.y] == 0) {
continue;
}
mark[temp.x][temp.y] = 1;
q.push(temp);
}
}
return -1;
}
};