leetcode 73. Set Matrix Zeroes (medium)

为了使用常数空间大小,将矩阵的第一行、第一列用来记录是否当前行、列需要全部置为0

class Solution
{
  public:
	void setZeroes(vector<vector<int>> &matrix)
	{
		size_t m = matrix.size();
		size_t n = matrix[0].size();
		bool row_zero = false;
		bool col_zero = false;
		for (size_t i = 0; i < n; i++)
		{
			if (matrix[0][i] == 0)
			{
				row_zero = true;
				break;
			}
		}
		for (size_t i = 0; i < m; i++)
		{
			if (matrix[i][0] == 0)
			{
				col_zero = true;
				break;
			}
		}
		for (size_t i = 1; i < m; i++)
			for (size_t j = 1; j < n; j++)
				if (matrix[i][j] == 0)
				{
					matrix[i][0] = 0;
					matrix[0][j] = 0;
				}
		for (size_t i = 1; i < m; i++)
			for (size_t j = 1; j < n; j++)
				if (matrix[i][0] == 0 || matrix[0][j] == 0)
					matrix[i][j] = 0;
		if (row_zero)
			for (size_t i = 0; i < n; i++)
			{
				matrix[0][i] = 0;
			}
		if (col_zero)
			for (size_t i = 0; i < m; i++)
			{
				matrix[i][0] = 0;
			}
	}
};
上一篇:【LeetCode】19.Array and String — Move Zeroes 移动零


下一篇:Leetcode-3-无重复字符的最长字串(滑动窗口)