leetcode 542 01 矩阵 BFS 动态规划

解题思路: 如果从元素为1 的开始做bfs, 时间复杂度为O(N^2 * M^2)算法会超时;

从元素为0开始做bfs, 时间复杂度为O(N*M), 不会导致超时。 另外需要将所有值为0 的元素全部入队列之后,  才开始开始第一轮的bfs, 可以确保所有为0 的元素开始向外扩展

动态规划思路: 从左下 和右上的两个方向进行 dp的计算

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
typedef struct {
    int x;
    int y;
    int num;
} Queue_t;
#define MAX_DIRECTION 4
typedef struct {
    int x;
    int y;
} Trans_Map_t;
Trans_Map_t Trans_Map[] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}, };  //l u r d
int** updateMatrix(int** matrix, int matrixSize, int* matrixColSize, int* returnSize, int** returnColumnSizes)
{
    if(matrix == NULL || matrixSize <= 0 || matrixColSize == NULL || returnSize == NULL || returnColumnSizes == NULL) {
        *returnSize = 0;
        return NULL;
    }
    int row = matrixSize;
    int col = *matrixColSize;
    Queue_t *Map = (Queue_t *)calloc(10 * row * col, sizeof(Queue_t));
    int ** visit = (int **)calloc(row, sizeof(int *));
    for (int i = 0; i < row; i++) {
        visit[i] = (int *)calloc(col, sizeof(int));
    }
    int front = 0;
    int rear = 0;
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            if (matrix[i][j] == 0) {
                Map[rear].x = i;
                Map[rear++].y = j;
                visit[i][j] = 1;
            } else {
                matrix[i][j] = -1;;
            }
        }
    }
    while (rear >= front) {
        Queue_t current = Map[front++];
        for (int i = 0; i < MAX_DIRECTION; i++) {
            Queue_t next;
            next.x = current.x + Trans_Map[i].x;
            next.y = current.y + Trans_Map[i].y;
            if(next.x < 0 || next.x > (row -1) || next.y < 0 || next.y > (col - 1) || visit[next.x][next.y] == 1) {
                continue;
            }
            next.num = current.num + 1;
            matrix[next.x][next.y] = next.num;
            visit[next.x][next.y] = 1;
            Map[rear++] = next;
        }
    }
    free(Map);
    for (int i = 0; i < row; i++) {
        free(visit[i]);
    }
    free(visit);
    *returnSize = row;
    *returnColumnSizes = (int *)malloc(sizeof(int) * row);
    for (int i = 0; i < row; i++) {
        (*returnColumnSizes)[i] = col;
    }
    return matrix;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值