[LeetCode] Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

问题描述:给定一个m * n的矩阵,如果某个元素为0,就把将该元素所在的行和列都置为0,要求原地操作。

最简单的方式是采用O(mn)的额外存储空间,如果某个元素所在的行或者列有0,就将该值所在的位置对应的位置置0,当然,这样的话空间复杂度就很高了。另外一种方式是采用O(m + n)的额外存储空间用于记录每行和每列是否有0,之后再对行或者列存在0的元素置0。

这里参考的别人的思路:用第一行和第一列的元素来记录该行和该列是否有0。

class Solution {
public:
	void setZeroes(vector > &matrix)
	{
		int row = matrix.size();
		if(row == 0) {
			return;
		}

		int col = matrix[0].size();
		if(col == 0) {
			return;
		}

		bool r0 = false, c0 = false;
		int i = 0;
		for(i = 0; i < col; ++i) {
			if(matrix[0][i] == 0) {
				r0 = true;
				break;
			}
		}

		for(i = 0; i < row; ++i) {
			if(matrix[i][0] == 0) {
				c0 = true;
				break;
			}
		}

		int j = 0;
		for(i = 1; i < row; ++i) {
			for(j = 1; j < col; ++j) {
				if(matrix[i][j] == 0) {
					matrix[i][0] = 0;
					matrix[0][j] = 0;
				}
			}
		}

		for(i = 1; i < row; ++i) {
			for(j = 1; j < col; ++j) {
				if(matrix[i][0] == 0 || matrix[0][j] == 0) {
					matrix[i][j] = 0;
				}
			}
		}

		if(r0) {
			for(j = 0; j < col; ++j) {
				matrix[0][j] = 0;
			}
		}
		if(c0) {
			for(i = 0; i < row; ++i) {
				matrix[i][0] = 0;
			}
		}
	}
};

由于需要使用第一行和第一列来存储该行列的关于0的信息,因此,为了不让第一行和第一列本身的元素造成影响,在获得置0信息之前,要判断第一行和第一列是否有0,然后在进行清0动作之后,要根据之前第一行和第一列的信息对第一行和第一列进行置0。

参考资料:

http://blog.csdn.net/magisu/article/details/16355975

你可能感兴趣的:(C++,algorithm,leetcode)