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;
}
相关推荐
历程里程碑2 小时前
各种排序法大全
c语言·数据结构·笔记·算法·排序算法
树在风中摇曳2 小时前
带哨兵位的双向循环链表详解(含 C 代码)+ LeetCode138 深度解析 + 顺序表 vs 链表缓存机制对比(图解 CPU 层级)
c语言·链表·缓存
雨落在了我的手上3 小时前
C语言入门(二十一):字符函数和字符串函数(1)
c语言
embrace993 小时前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程
EXtreme354 小时前
深入浅出数据结构:手把手实现动态顺序表,从此不再怕数组扩容!
c语言·顺序表·malloc·realloc
smj2302_7968265212 小时前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
薛慕昭15 小时前
嵌入式 C 语言猜大小游戏设计与实现
c语言·游戏
leoufung15 小时前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
月光技术杂谈16 小时前
实战:C驱动框架嵌入Rust模块的互操作机制与完整流程
c语言·开发语言·rust·ffi·跨语言·bindgen·互操作
im_AMBER16 小时前
Leetcode 59 二分搜索
数据结构·笔记·学习·算法·leetcode