Open carloscn opened 1 year ago
struct pos_t {
size_t x;
size_t y;
};
int32_t set_to_zero(int64_t* matrix, size_t len, size_t depth, struct pos_t pos)
{
int32_t ret = 0;
UTILS_CHECK_PTR(matrix);
UTILS_CHECK_LEN(len);
UTILS_CHECK_LEN(depth);
size_t i = 0;
// set row
for (i = 0; i < len; i ++) {
*(matrix + pos.y * len + i) = 0;
}
// set column
for (i = 0; i < depth; i ++) {
*(matrix + i * len + pos.x) = 0;
}
finish:
return ret;
}
int32_t set_zeroes(int64_t* matrix, size_t len, size_t depth)
{
int32_t ret = 0;
struct pos_t *pos_buffer = NULL;
UTILS_CHECK_PTR(matrix);
UTILS_CHECK_LEN(len);
UTILS_CHECK_LEN(depth);
size_t i = 0, j = 0;
size_t k = 0;
pos_buffer = (struct pos_t *)calloc(len * depth, sizeof(struct pos_t));
UTILS_CHECK_PTR(pos_buffer);
for (i = 0; i < depth; i ++) {
for (j = 0; j < len; j ++) {
if (0 == *(matrix + i * len + j)) {
pos_buffer[k].x = j;
pos_buffer[k ++].y = i;
}
}
}
for (i = 0; i < k; i ++) {
ret = set_to_zero(matrix, len, depth, pos_buffer[i]);
UTILS_CHECK_RET(ret);
}
finish:
UTILS_SAFE_FREE(pos_buffer);
return ret;
}
问题描述
给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
示例 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]] 输出:[[1,0,1],[0,0,0],[1,0,1]]
示例 2:
输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
提示:
m == matrix.length n == matrix[0].length 1 <= m, n <= 200 -231 <= matrix[i][j] <= 231 - 1
进阶:
一个直观的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。 你能想出一个仅使用常量空间的解决方案吗?
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/set-matrix-zeroes