做力扣的 542. 01 矩阵 题的时候,两个代码执行的速度有差距,第一个使用vector 用时200ms;第二个使用数组用时 68ms。
代码一
class Solution {
private:
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { // 超时?
queue<pair<int, int>> q;
pair <int, int> point;
vector<vector<int>>neibourhood = {
{0,-1},{0,1},{-1,0},{1,0}
};
int row = mat.size(), col = mat[0].size();
vector<vector<int>> result(row, vector<int>(col));
vector<vector<int>> passed(mat.size(), vector<int>(mat[0].size())); // ? 他们有没有 pass ?
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (mat[i][j] == 0)
{
q.emplace(i,j);
passed[i][j] = 1;
//result[i][j] = 0;
}
}
}
while (!q.empty() )
{
point = q.front();
q.pop();
// 找这个节点的邻居
for (auto v : neibourhood)
{
int new_row = point.first + v[0];
int new_col = point.second + v[1];
//if (new_row >= mat.size() || new_row < 0 || new_col >= mat[0].size() || new_col < 0) continue;
if (new_row >= 0 && new_row < row && new_col >= 0 && new_col < col && !passed[new_row][new_col])
{
result[new_row][new_col] = result[point.first][point.second] + 1;
q.emplace(new_row, new_col);
passed[new_row][new_col] = 1;
}
}
}
return result;
}
};
代码二
class Solution {
private:
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { // 超时?
queue<pair<int, int>> q;
pair <int, int> point;
vector<vector<int>>neibourhood2 = {
{0,-1},{0,1},{-1,0},{1,0}
};
int neibourhood[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int row = mat.size(), col = mat[0].size();
vector<vector<int>> result(row, vector<int>(col));
vector<vector<int>> passed(mat.size(), vector<int>(mat[0].size())); // ? 他们有没有 pass ?
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (mat[i][j] == 0)
{
q.emplace(i,j);
passed[i][j] = 1;
//result[i][j] = 0;
}
}
}
while (!q.empty() )
{
point = q.front();
q.pop();
// 找这个节点的邻居
for (auto v : neibourhood)
{
int new_row = point.first + v[0];
int new_col = point.second + v[1];
//if (new_row >= mat.size() || new_row < 0 || new_col >= mat[0].size() || new_col < 0) continue;
if (new_row >= 0 && new_row < row && new_col >= 0 && new_col < col && !passed[new_row][new_col])
{
result[new_row][new_col] = result[point.first][point.second] + 1;
q.emplace(new_row, new_col);
passed[new_row][new_col] = 1;
}
}
}
return result;
}
};
有人知道这是为什么…