LeetCode 542. 01 矩阵

题目描述:给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

class Solution {
public:
	bool isExist(vector<vector<int>>& matrix, const int& j, const int& k, const int& i, const int& rows, const int& cols) {
		if (j - 1 >= 0) {
			if (matrix[j - 1][k] == i)return true;
		}
		if (j + 1 < rows) {
			if (matrix[j + 1][k] == i)return true;
		}
		if (k - 1 >= 0)
			if (matrix[j][k - 1] == i)return true;
		if (k + 1 < cols)
			if (matrix[j][k + 1] == i)return true;
		return false;
	}
	vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
		unsigned int rows = matrix.size();
		unsigned int cols = matrix[0].size();
		int unsigned num = 0;
		for (int j = 0; j < rows; j++) {
			for (int k = 0; k < cols; k++) {
				if (matrix[j][k] == 0)
					num++;
				else
					matrix[j][k] = 10001;
			}
		}
		unsigned int i = 0;
		while (num != rows * cols) {
			for (int j = 0; j < rows; j++) {
				for (int k = 0; k < cols; k++) {
					if (matrix[j][k] > i){
						if (isExist(matrix, j, k, i, rows, cols)) {
							matrix[j][k] = i + 1;
							num++;
						}
					}	
				}
			}
			i++;
		}
		return matrix;
	}
};

  

posted @ 2020-04-15 11:39  airfy  阅读(130)  评论(0)    收藏  举报