각각의 셀마다 가장 가까운 0의 거리는?
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
class Solution {
std::queue<pair<int, int>> q;
int rsize;
int csize;
vector<vector<int>> visit; // 수행속도는 함수 매개변수로 넘기는 방식이 더 빨랐음.
void inc_count_push(vector<vector<int>> &mat, int r, int c) {
int pos_val = mat[r][c];
// check 4 direction from pop position
// if on 4 each value is 1 -> increase by pos_val + 1
// then push it
if (r-1 >= 0 && visit[r-1][c] == 0 && mat[r-1][c] == 1) {
mat[r-1][c] = pos_val + 1;
q.push(make_pair(r-1, c));
visit[r-1][c] = 1;
}
if (r+1 < rsize && visit[r+1][c] == 0 && mat[r+1][c] == 1) {
mat[r+1][c] = pos_val + 1;
q.push(make_pair(r+1, c));
visit[r+1][c] = 1;
}
if (c-1 >= 0 && visit[r][c-1] == 0 && mat[r][c-1] == 1) {
mat[r][c-1] = pos_val + 1;
q.push(make_pair(r, c-1));
visit[r][c-1] = 1;
}
if (c+1 < csize && visit[r][c+1] == 0 && mat[r][c+1] == 1) {
mat[r][c+1] = pos_val + 1;
q.push(make_pair(r, c+1));
visit[r][c+1] = 1;
}
}
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
rsize = mat.size();
csize = mat[0].size();
//vector<vector<int>> visit(rsize, vector<int> (csize, 0));
visit = vector<vector<int>> (rsize, vector<int> (csize, 0));
for (int i = 0; i < rsize; i++) {
for (int j = 0; j < csize; j++) {
if (mat[i][j] == 0)
q.push(make_pair(i, j));
}
}
while (!q.empty()) {
pair<int, int> pos = q.front();
q.pop();
inc_count_push(mat, pos.first, pos.second);
}
return mat;
}
};
숙지하자.
vector<vector<int>> visit(rsize, vector<int> (csize, 0));
vector<vector<int>> visit; //전역 선언
visit = vector<vector<int>> (rsize, vector<int> (csize, 0)); //초기화