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;
}
相关推荐
求梦8201 天前
【力扣hot100题】旋转图像(15)
算法·leetcode·职场和发展
SmartRadio1 天前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
cpp_25011 天前
P2708 硬币翻转
数据结构·c++·算法·题解·洛谷
踩坑记录1 天前
leetcode hot100 11.盛最多水的容器 medium 双指针
算法·leetcode·职场和发展
圣保罗的大教堂1 天前
leetcode 865. 具有所有最深节点的最小子树 中等
leetcode
X在敲AI代码1 天前
LeetCode 基础刷题D2
算法·leetcode·职场和发展
源代码•宸1 天前
Leetcode—1929. 数组串联&&Q1. 数组串联【简单】
经验分享·后端·算法·leetcode·go
weixin_461769401 天前
15. 三数之和
c++·算法·leetcode·三数之和
千金裘换酒1 天前
LeetCode 链表两数相加
算法·leetcode·链表
SmartRadio2 天前
在CH585M代码中如何精细化配置PMU(电源管理单元)和RAM保留
linux·c语言·开发语言·人工智能·单片机·嵌入式硬件·lora