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;
}
相关推荐
艾莉丝努力练剑10 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
Cx330❀12 小时前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法
..过云雨13 小时前
01.【数据结构-C语言】数据结构概念&算法效率(时间复杂度和空间复杂度)
c语言·数据结构·笔记·学习
谱写秋天15 小时前
在STM32F103上进行FreeRTOS移植和配置(STM32CubeIDE)
c语言·stm32·单片机·freertos
我不是板神15 小时前
程序设计|C语言教学——C语言基础2:计算与控制语句
c语言
基于python的毕设15 小时前
C语言栈的实现
linux·c语言·ubuntu
promising-w19 小时前
【嵌入式C语言】六
c语言·开发语言
ankleless19 小时前
C语言(11)—— 数组(超绝详细总结)
c语言·零基础·数组·二维数组·自学·一维数组
一匹电信狗20 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
草莓熊Lotso21 小时前
《吃透 C++ 类和对象(中):const 成员函数与取地址运算符重载解析》
c语言·开发语言·c++·笔记·其他