# leetcode[73] Set Matrix Zeroes 将矩阵置零

1 2 3

1 0 3

1 1 1

1 0 3

0 0 0

1 0 1

class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
int len1 = matrix.size();
if (len1 == 0) return ;
int len2 = matrix[0].size();
if (len2 == 0) return ;
vector<bool > row(len1), col(len2);
for (int i = 0; i < len1; i++)
for (int j = 0; j < len2; j++)
{
if (matrix[i][j] == 0)
{
row[i] = true; col[j] = true;
}
}
for (int i = 0; i < len1; i++)
for (int j = 0; j < len2; j++)
{
if (row[i] == true)
matrix[i][j] = 0;
else if (col[j] == true)
matrix[i][j] = 0;
}
return ;
}
};

1. 找到一个零的位置，把这行这列当做方法2中的两个数组存值。

2. 根据1的位置的所在行和列的值是否有零将矩阵相应位置置零。

3. 再把1中零所在位置的行和列置零。

class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
int len1 = matrix.size();
if (len1 == 0) return ;
int len2 = matrix[0].size();
if (len2 == 0) return ;
int row = -1, col = -1;
for (int i = 0; i < len1; i++)
for (int j = 0; j < len2; j++)
{
if (matrix[i][j] == 0)
{
row = i; col = j;
}
}
if (row == -1) return;
for (int i = 0; i < len1; i++)
for (int j = 0; j < len2; j++)
{
if (matrix[i][j] == 0 && i != row && j != col)
{
matrix[i][col] = 0;
matrix[row][j] = 0;
}
}
for (int i = 0; i < len1; i++)
for (int j = 0; j < len2; j++)
{
if (i != row && j != col)
{
if (matrix[i][col] == 0 )
matrix[i][j] = 0;
else if (matrix[row][j] == 0)
matrix[i][j] = 0;
}
}
int index = -1;
while(++index < len1) matrix[index][col] = 0;
index = -1;
while(++index < len2) matrix[row][index] = 0;
return ;
}
};

2015/03/25:

Python:

class Solution:
# @param matrix, a list of lists of integers
# @return nothing (void), do not return anything, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
if len(matrix) == 0:
return ;
row, col = 1, 1
for i in range(0, len(matrix)):
if matrix[i][0] == 0:
col = 0
for j in range(0, len(matrix[0])):
if matrix[0][j] == 0:
row = 0

for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0

if col == 0:
for i in range(0, len(matrix)):
matrix[i][0] = 0
if row == 0:
for j in range(0, len(matrix[0])):
matrix[0][j] = 0

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

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