01 Matrix_Week11
题目说明:
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 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
难度: Medium
解题思路:
题意由Examples可轻松得知,即给定0 1矩阵,给出其距离矩阵,距离为每个位置离其最近的0的曼哈顿距离
我最初的思路是暴力解决问题(…),即遍历一遍矩阵,先用一个vector存下所有的0,然后再遍历一遍数组,将数组中每个位置对于每个0的位置的曼哈顿距离都算出来,算出最小的,即是该距离的值。(果然很暴力)
但是我知道这道题肯定不是让我这样做所以这样出的…其实最开始的思路并不是暴力解决问题,而是通过遍历矩阵,传播距离。每个位置计算其周围8个(或4个)方向上是否存在0或者存在已计算出的最小距离,通过其可以得到其距离值。一开始觉得一次遍历成功不了就放弃了这个想法(后来想想肯定不能一次遍历就得到结果啊…需要多次迭代)。下面先贴出暴力解决的方法:(因为多层迭代递归的方法还没写完…等能AC了再放上来,这周再钻研钻研)
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& A) {
int size1 = A.size();
int size2 = A[0].size();
int i, j, k;
//用于记录所有0的位置
vector<pair<int,int> > zeroPos;
//函数的返回结果:距离矩阵distance
vector<vector<int> > distance = A;
//第一次遍历将所有的0找到并加入vector
for (i = 0; i < size1; i++) {
for (j = 0; j < size2; j++) {
distance[i][j] = 9999;
if (A[i][j] == 0) {
zeroPos.push_back(pair<int,int>(i,j));
distance[i][j] = 0;
}
}
}
int size3 = zeroPos.size();
//第二次遍历将所有位置离其最近0的位置算出来
for (i = 0; i < size1; i++) {
for (j = 0; j < size2; j++) {
if (A[i][j] == 0 || distance[i][j] <= 1) {
continue;
} else {
int minDis = 9999;
int tempDis = 0;
for (k = 0; k < size3; k++) {
tempDis = dis(pair<int,int>(i,j),zeroPos[k]);
if (tempDis < distance[i][j]) {
distance[i][j] = tempDis;
//若算出1,已经是最小距离,直接返回
if (tempDis == 1) break;
}
}
}
}
}
return distance;
}
//用于计算两个点的曼哈顿距离
int dis(pair<int,int> a, pair<int,int> b) {
int dis = 0;
dis += abs(a.first - b.first);
dis += abs(a.second - b.second);
return dis;
}
};