解题思路: 如果从元素为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;
}