01 Matrix LeetCode solution in C++
1class Solution {2public:3vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {4queue<pair<int, int>> q;5for (int i = 0; i < mat.size(); i++) {6for (int j = 0; j < mat[0].size(); j++) {7if (mat[i][j] == 0)8q.push({i, j});9else10mat[i][j] = -1;11}12}13int length = 0;14int dirx[] = {1, -1, 0, 0};15int diry[] = {0, 0, 1, -1};16while (!q.empty()) {17int size = q.size();18length++;19while (size--) {20auto f = q.front();21q.pop();22int s = f.first;23int end = f.second;24for (int i = 0; i < 4; i++) {25int r = s + dirx[i];26int c = end + diry[i];27if (r < 0 || c < 0 || r == mat.size() || c == mat[0].size() || mat[r][c] != -1) continue;28mat[r][c] = length;29q.push({r, c});30}31}32}33return mat;34}35};