1765. Map of Highest Peak

ss
Feb 21, 2021

--

這題我寫的時候蠻興奮的, 這題跟

01 Matrix

幾乎是一模一樣的, 詳情可以點進去看連結,

採用bfs

class Solution {
public:
vector<vector<int>> highestPeak(vector<vector<int>>& iw) {
int m = iw.size();
int n = iw[0].size();
vector<vector<int>> res (m, vector<int>(n, INT_MAX));
queue<pair<int, int>> q;
for(int i = 0 ; i < m ;i++){
for(int j = 0;j < n;j++){
if(iw[i][j] == 1){
res[i][j] = 0;
q.push({i, j});
}
}
}
vector<vector<int>> dirs{ {1,0}, {-1, 0}, {0, 1}, {0, -1}};
while(!q.empty()){
pair<int, int> cur = q.front();
q.pop();
int i = cur.first;
int j = cur.second;
for(auto dir: dirs){
int x = i + dir[0];
int y = j + dir[1];
if(x < 0 || x >= m || y <0 || y >= n){
continue;
}
if(res[x][y] > res[i][j] + 1){
res[x][y] = res[i][j] + 1;
q.push({x, y});
}
}
}
return res;
}
};

--

--

ss
ss

No responses yet