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;
}
相关推荐
laocooon5238578861 小时前
win操作系统安装C++语言开发环境之一, vscode +MinGW ,流程
c语言
奔跑吧邓邓子1 小时前
解锁Vscode:C/C++环境配置超详细指南
c语言·c++·vscode·配置指南
不7夜宵2 小时前
力扣热题100 k个一组反转链表题解
算法·leetcode·链表
蒟蒻小袁3 小时前
力扣面试150题--课程表
算法·leetcode·面试
AL流云。4 小时前
【优选算法】分治
数据结构·算法·leetcode·排序算法
小柯博客9 小时前
从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(十二)
c语言·stm32·单片机·嵌入式硬件·php·嵌入式
chengooooooo11 小时前
leetcode Top100 238. 除自身以外数组的乘积|数组系列
算法·leetcode
乄夜13 小时前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
GalaxyPokemon15 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展