542. 01 矩阵 - 力扣(LeetCode) (leetcode-cn.com)
今天的题有点小难,但是解法很多。
DP解法:
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m=mat.size(),n=mat[0].size();
vector<vector<int>> res=mat;
for(int i=0;i<m;i++)for(int j=0;j<n;j++)if(res[i][j])res[i][j]=INT_MAX-1;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
if(res[i][j]){
if(i>0)res[i][j]=min(res[i][j],res[i-1][j]+1);
if(j>0)res[i][j]=min(res[i][j],res[i][j-1]+1);
}
}
for(int i=m-1;i>=0;i--)
for(int j=n-1;j>=0;j--){
if(res[i][j]){
if(i<m-1)res[i][j]=min(res[i][j],res[i+1][j]+1);
if(j<n-1)res[i][j]=min(res[i][j],res[i][j+1]+1);
}
}
return res;
}
};
class Solution {
public:
const pair<int, int> D[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int row=mat.size();
int col=mat[0].size();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
// 优化:如果元素在 0 附近,保留元素值 1,不在 0 附近,初始化为一个较大值
if (mat[i][j] == 1
&& !((i > 0 && mat[i - 1][j] == 0)
|| (i < row - 1 && mat[i + 1][j] == 0)
|| (j > 0 && mat[i][j - 1] == 0)
|| (j < col - 1 && mat[i][j + 1] == 0))) {
mat[i][j] = 10000;
}
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
// 优化:将元素值为 1 的点作为深搜起点,降低递归深度
if (mat[i][j] == 1) {
dfs(mat, i, j);
}
}
}
return mat;
}
private:
void dfs(vector<vector<int>>& mat, int r, int c) {
int row=mat.size();
int col=mat[0].size();
const int dy[4] = {-1, 0, 1, 0};
const int dx[4] = {0, -1, 0, 1};
for (int i=0;i<4;i++)
{
int nr = r+ dx[i];
int nc = c + dy[i];
if (nr >= 0 && nr < row && nc >= 0 && nc < col && mat[nr][nc] > mat[r][c]+1 ) {
mat[nr][nc] =mat[r][c] + 1;
dfs(mat, nr, nc);
}
}}
};
994. 腐烂的橘子 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
if ( grid.size() == 0) {
return 0;
}
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == 2) {
dfs(grid,i, j, 2); // 开始传染
}
}
}
// 经过dfs后,grid数组中记录了每个橘子被传染时的路径长度,找出最大的长度即为腐烂全部橘子所用的时间。
int maxLevel = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == 1) {
return -1; // 若有新鲜橘子未被传染到,直接返回-1
} else {
maxLevel = max(maxLevel, grid[i][j]);
}
}
}
return maxLevel == 0? 0: maxLevel - 2;
}
void dfs(vector<vector<int>>& grid,int i, int j, int level) { // level用来记录传染路径的长度(当然最后要减2)
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() ) {
return;
}
if (grid[i][j] != 1 && grid[i][j] < level) { // 只有新鲜橘子或者传播路径比当前路径长的橘子,才继续进行传播。
return;
}
grid[i][j] = level; // 将传染路径的长度存到grid[i][j]中
level++;
dfs(grid,i - 1, j, level);
dfs(grid,i + 1, j, level);
dfs(grid,i, j - 1, level);
dfs(grid,i, j + 1, level);
}
};