【LeetCode】20.Set Matrix Zeroes

题目描述(Medium)

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

题目链接

https://leetcode.com/problems/set-matrix-zeroes/description/

Example 1:

Input:
[
    [1,1,1],
    [1,0,1],
    [1,1,1]
]
Output:
[
    [1,0,1],
    [0,0,0],
    [1,0,1]
]

Example 2:

Input:
[
    [0,1,2,0],
    [3,4,5,2],
    [1,3,1,5]
]
Output:
[
    [0,0,0,0],
    [0,4,5,0],
    [0,3,1,0]
]

Follow up:

  • 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?

算法分析

复用第一行和第一列作为标志位。

提交代码:

class Solution {
public:
	// 使用第一行和第一列作为标志位
	void setZeroes(vector<vector<int>>& matrix) {
		const size_t m = matrix.size();
		const size_t n = matrix[0].size();
		bool row_has_zero = false;
		bool col_has_zero = false;

		for (size_t i = 0; i < n; ++i)
			if (!matrix[0][i])
			{
				row_has_zero = true;
				break;
			}

		for (size_t i = 0; i < m; ++i)
			if (!matrix[i][0])
			{
				col_has_zero = true;
				break;
			}

		for (size_t i = 1; i < m; ++i)
			for (size_t j = 1; j < n; ++j)
				if (!matrix[i][j])
				{
					matrix[0][j] = 0;
					matrix[i][0] = 0;
				}

		for (size_t i = 1; i < m; ++i)
			for (size_t j = 1; j < n; ++j)
				if (!matrix[0][j] || !matrix[i][0])
					matrix[i][j] = 0;

		if (row_has_zero)
			for (size_t i = 0; i < n; ++i)
				matrix[0][i] = 0;

		if (col_has_zero)
			for (size_t i = 0; i < m; ++i)
				matrix[i][0] = 0;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<vector<int>>& matrix, vector<vector<int>>& expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	s.setZeroes(matrix);

	if (matrix == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{
	vector<vector<int>> matrix = {
		{ 1, 1, 1 },
		{ 1, 0, 1 },
		{ 1, 1, 1 }
	};
	vector<vector<int>> expected = {
		{ 1, 0, 1 },
		{ 0, 0, 0 },
		{ 1, 0, 1 }
	};
	Test("Test1", matrix, expected);

	matrix = {
		{ 0, 1, 2, 0 },
		{ 3, 4, 5, 2 },
		{ 1, 3, 1, 5 }
	};
	expected = {
		{ 0, 0, 0, 0 },
		{ 0, 4, 5, 0 },
		{ 0, 3, 1, 0 }
	};
	Test("Test2", matrix, expected);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82115944