Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1. Example 1:
Input:
0 0 0 0 1 0 0 0 0Output:
0 0 0 0 1 0 0 0 0
Example 2:
Input:
0 0 0 0 1 0 1 1 1Output:
0 0 0 0 1 0 1 2 1
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
Subscribe to see which companies asked this question.
题意:0/1矩阵,对于每个1求出离他最近的0需要走多少步
思路:就一个简单的bfs,纯的,裸的,特别裸。。。
心情好复杂啊。。。搞清楚了以后觉得自己是个zz,这么简单的面试题我居然写了暴力。。。(求面试官心理阴影面积T T)
class Solution {
public:
struct node {
int x, y;
node() {}
node (int _x, int _y) {
x = _x;
y = _y;
}
};
vector<vector<int>> updateMatrix(vector<vector<int>>& a) {
int c = a.size(), r = a[0].size();
vector<vector<int>> ans(c, vector<int>(r, r + c));
queue<node> m;
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
if (a[i][j] == 0) {
m.push(node(i, j));
ans[i][j] = 0;
}
}
}
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
while (!m.empty()) {
node now = m.front();
m.pop();
for (int i = 0; i < 4; i++) {
int nx = now.x + dir[i][0];
int ny = now.y + dir[i][1];
while (nx >=0 && nx < c && ny >= 0 && ny < r && ans[nx][ny] == r + c) {
m.push(node(nx, ny));
ans[nx][ny] = ans[now.x][now.y] + 1;
}
}
}
return ans;
}
};
啊,再贴个男票写的~
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int n = matrix.size(),m = matrix[0].size();
vector<vector<int>> res(n,vector<int>(m,n+m));
queue<pair<int,int>> Q;
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
if(matrix[i][j] == 0) Q.push(make_pair(i,j)),res[i][j] = 0;
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
while(!Q.empty()) {
auto u = Q.front(); Q.pop();
for(int i=0;i<4;++i){
int x = u.first + dx[i],y = u.second + dy[i];
if(x >= 0 && y >= 0 && x < n && y < m && res[x][y] == m+n){
res[x][y] = res[u.first][u.second] + 1;
Q.push(make_pair(x,y));
}
}
}
return res;
}