73. Set Matrix Zeroes

73. 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.

click to show follow up.
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?

解析

  • 使用额外的空间的话,就是做两个一维数组,分别标记哪一行哪一列有0,然后把这些行和列都清0即可。这样空间复杂度为O(m+n);

  • 不使用额外空间的方法类似,就是把第一行和第一列作为标记。 首先 先判断第一行第一列是否含有0,并用两个bool变量记录起来。其次,遍历其他行和列,如果有0,就把该元素所在的行和列 分别记录起来,即把第一列的该行置0,把第一行的该列置为0;比如 matrix[1][2]==0,那么,把matrix[i][0]和matrix[0][j]都置零。这样,遍历一遍之后就把所有的行和列都在第一行和第一列中体现出来。接下来就是,根据第一行和第一列的0元素,把其所在的行和列置0,不包括第一行和第一列。再接下来,就是根据前面的bool标记判断是否把第一行和第一列置零。

class Solution_73 {
public:
	void setZeroes(vector<vector<int> > &matrix) {
		
		int n = matrix.size();
		int m = matrix[0].size();
		
		bool row = false, col = false;
		//记录第一行,第一列是否有0
		for (int i = 0; i < n;i++)
		{
			if (matrix[i][0]==0)
			{
				row = true;
				break;
			}
		}
		for (int j = 0; j < m;j++)
		{
			if (matrix[0][j]==0)
			{
				col = true;
				break;
			}
		}

		//遍历其他位置,用第一行,第一列记录是否有0
		for (int i = 1; i < n;i++)
		{
			for (int j = 1; j < m;j++)
			{
				if (matrix[i][j]==0)
				{
					matrix[i][0] = 0;
					matrix[0][j] = 0;
				}
			}
		}

		//根据记录清0
		for (int i = 1; i < n;i++)
		{
			for (int j = 1; j < m;j++)
			{
				if (0==matrix[i][0]||0==matrix[0][j])
				{
					matrix[i][j] = 0;
				}
			}
		}

		// 处理第一行/列
		if (row)
		{
			for (int i = 0; i < n;i++)
			{
				matrix[i][0] = 0;
			}
		}
		if (col)
		{
			for (int j = 0; j < m;j++)
			{
				matrix[0][j] = 0;
			}
		}
		return;
	}
};

题目来源

原文地址:https://www.cnblogs.com/ranjiewen/p/8676751.html