C语言 | Leetcode C语言题解之第542题01矩阵

题目:

题解:

cpp 复制代码
/**
 * 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;
}coordinate;//坐标结构体


int** updateMatrix(int** mat, int matSize, int* matColSize, int* returnSize, int** returnColumnSizes){

    int dx[4]={-1,0,1,0};//用作坐标偏移
    int dy[4]={0,-1,0,1};

    //新建队列,存放坐标数组
    coordinate* queue=(coordinate*)malloc(sizeof(coordinate) * 10240);
    int front=0;
    int rear=0;

    //设置结果数组返回值
    *returnSize=matSize;
    *returnColumnSizes=matColSize;//returnColumnSizes是一个二级指针,解引用之后是一个一级指针,可以直接等于
    
    //定义二级指针,申请空间构建二维数组当结果
    int** result=(int**)malloc(sizeof(int*) * matSize);//申请matSize个空间存储每一个行指针
    for(int i=0;i<matSize;i++)
    {
        //result[i]=(int*)malloc(sizeof(int) * (*matColSize)); 
        *(result+i)=(int*)malloc(sizeof(int) * (*matColSize));//给行指针申请*matColSize个空间
        
        //初始化二维数组--原数组为0的地方初始化为0,为1的地方初始化化为max,方便后面进行距离比较
        for(int j=0;j<*matColSize;j++)
        {
            if(mat[i][j]==0)
            {
                result[i][j]=0;
                queue[rear].x=i;
                queue[rear].y=j;//将该坐标入队
                rear++;//队尾指针后移一位,指向空
            }
            else
            {
                result[i][j]=INT_MAX;//INT_MAX --> 整数类型所能表达的最大值
            }
        }
    }

    
    //开始进行广度优先搜索
    int x,y;//扩散后的坐标
    while(front!=rear)
    {
        for(int i=0;i<4;i++)
        {
            x=queue[front].x+dx[i];
            y=queue[front].y+dy[i];
            
            if(x>=0 && x<matSize && y>=0 && y<*matColSize)
            {
                //result[x][y]为INT_MAX的时候
                if(result[x][y] > result[queue[front].x][queue[front].y]+1)
                {
                    result[x][y] = result[queue[front].x][queue[front].y]+1;
                    queue[rear].x=x;//将新的已经被赋值所求距离的位置坐标入队
                    queue[rear].y=y;
                    rear++;
                }
            }
        }
        front++;//队列头指针后移,接着往后遍历
    }
    return result;
}
相关推荐
愚者游世27 分钟前
力扣解决二进制&题型常用知识点梳理
c++·程序人生·算法·leetcode·职场和发展·改行学it
圣保罗的大教堂27 分钟前
leetcode 3640. 三段式数组 II 困难
leetcode
Geoking.30 分钟前
前缀和算法:从一道 LeetCode 题看区间求和优化思想
算法·leetcode·职场和发展
执着25940 分钟前
力扣102、二叉树的层序遍历
数据结构·算法·leetcode
Tisfy42 分钟前
LeetCode 2976.转换字符串的最小成本 I:floyd算法(全源最短路)
算法·leetcode··floyd·题解
v_for_van1 小时前
力扣刷题记录4(无算法背景,纯C语言)
c语言·算法·leetcode
启友玩AI1 小时前
方言守护者:基于启英泰伦CI-F162GS02J芯片的“能听懂乡音”的智能夜灯DIY全攻略
c语言·人工智能·嵌入式硬件·ai·语音识别·pcb工艺
EmbedLinX1 小时前
Linux 之设备驱动
linux·服务器·c语言
smj2302_796826522 小时前
解决leetcode第3826题.最小分割分数问题
数据结构·python·算法·leetcode
VT.馒头2 小时前
【力扣】2705. 精简对象
javascript·数据结构·算法·leetcode·职场和发展·typescript