LeetCode
来源:互联网 发布:淘宝中国质造加入条件 编辑:程序博客网 时间:2024/06/06 03:07
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 00 1 00 0 0Output:
0 0 00 1 00 0 0
Example 2:
Input:
0 0 00 1 01 1 1Output:
0 0 00 1 01 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;}
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- android:clipToPadding的使用详解
- triangle
- 最短的名字 字典树
- Java考试基础知识回顾
- 时间转换:秒转String
- LeetCode
- Lucene总结系列(三)--总述优化方案和呈现实时内存索引实现(结合RAMDirectory源码解析)
- Unity3D学习(6)——简易飞碟游戏
- TCP的交互数据流
- 解决AndroidStudio导入项目在 Building gradle project info 一直卡住
- form表单中的encType属性
- Map 遍历
- ssh安装及免密登录使用说明
- bzoj1294: [SCOI2009]围豆豆Bean