[LeetCode]Set Matrix Zeroes

本文介绍了一种高效的矩阵置零算法,该算法通过利用矩阵的第一行和第一列来标记需要置零的位置,从而避免使用额外的空间。文章提供了详细的C++实现代码,并通过两个不同的类展示了如何在不改变矩阵原始大小的情况下,将包含0元素的行和列全部置零。
class Solution {
//let the first row and first col to keep the record
//if matrix[row][col] == 0 && col == 0, then firstColZero = true, same to firstRowZero
public:
	void setZeroes(vector<vector<int> > &matrix) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int rowNum = matrix.size();
		if(0 == rowNum) return;
		int colNum = matrix[0].size();

		bool firstRowZero, firstColumnZero;
		firstRowZero = firstColumnZero = false;
		for (int row = 0; row < rowNum; ++row)
		{
			for (int col = 0; col < colNum; ++col)
			{
				if (!matrix[row][col])
				{
					if(row == 0) firstRowZero = true;
					if(col == 0) firstColumnZero = true;
					matrix[row][0] = 0;
					matrix[0][col] = 0;
				}
			}
		}
		//according the flag in first row and first col to set the row and col to zero corresponding
		for(int row = 1; row < rowNum; ++row)
		{
			if(0 == matrix[row][0])
			{
				for (int col = 0; col < colNum; ++col)
					matrix[row][col] = 0;
			}
		}
		//
		for(int col = 1; col < colNum; ++col)
		{
			if(0 == matrix[0][col])
			{
				for (int row = 0; row < rowNum; ++row)
					matrix[row][col] = 0;
			}
		}
		//
		if(firstRowZero)
			for (int col = 0; col < colNum; ++col)
				matrix[0][col] = 0;
		if(firstColumnZero)
			for (int row = 0; row < rowNum; ++row)
				matrix[row][0] = 0;
	}
};

second time

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int n = matrix.size();
		if(n == 0) return;
		int m = matrix[0].size();
		if(m == 0) return;

		bool firstRow = false;
		bool firstColumn = false;

		for(int i = 0; i < n; ++i) 
		{
			if(matrix[i][0] == 0)
			{
				firstColumn = true;
				break;
			}
		}
		for(int j = 0; j < m; ++j) 
		{
			if(matrix[0][j] == 0)
			{
				firstRow = true;
				break;
			}
		}

		//using first row and first column to keep record
		for(int i = 1; i < n; ++i)
		{
			for(int j = 1; j < m; ++j)
			{
				if(matrix[i][j] == 0) matrix[0][j] = 0, matrix[i][0] = 0;
			}
		}
		//set zero
		for(int i = 1; i < n; ++i)
		{
			if(matrix[i][0] == 0) 
			{
				for(int j = 1; j < m; ++j) matrix[i][j] = 0;
			}
		}
		for(int j = 1; j < m; ++j)
		{
			if(matrix[0][j] == 0)
			{
				for(int i = 1; i < n; ++i) matrix[i][j] = 0;
			}
		}
		//set first row and first colum
		if(firstRow) 
		{
			for(int j = 0; j < m; ++j) matrix[0][j] = 0;
		}
		if(firstColumn)
		{
			for(int i = 0; i < n; ++i) matrix[i][0] = 0;
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值