力扣54力扣59螺旋矩阵c语言合集
力扣螺旋矩阵的整理,以后看见还会更新
力扣54螺旋矩阵
题目描述
思想
关键点:
1:因为是螺旋的方法进行旋转,那么定义出对应的操作顺序为:左下右上
2:循环输出,判断到达边界或则之前访问过的切换模式便可
代码
int movrow[4]={0,1,0,-1};
int movcol[4]={1,0,-1,0};//定义右下左上
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize)
{
if(matrixSize == 0 || matrixColSize[0] == 0)//如果二维数组为空,则直接return NULL
{
*returnSize = 0;
return NULL;
}
int *returnnum = (int*)malloc(sizeof(int)*matrixSize*matrixColSize[0]);//定义一个一维数组为题目所求
*returnSize = matrixSize*matrixColSize[0];//返回长度应为行乘列
int row = 0;//定义二维数组的行
int col = 0;//定义二维数组的列
int count = 0;//一维数组的下标
int mode = 0;//模式即为二维数组应向哪个方向读取数字
int newrow = 0;//看看下一步的探索
int newcol = 0;
while(1)//定义死循环
{
returnnum[count++] = matrix[row][col];//一维数组读取数字
matrix[row][col] = 1;//二维数组读取过的数字做个特殊标记
newrow = row + movrow[mode];//行变化
newcol = col + movcol[mode];//列变化
if(newrow < 0 || newcol < 0 || newrow >= matrixSize || newcol >= matrixColSize[0] || matrix[newrow][newcol] == 1)
//如果新探索的行和列小于0或大于所给长度,以及下一步是已经读取过的数字应该转换方向
{
mode = (mode + 1) % 4;//转换方向,这步很简洁
newrow = row + movrow[mode];//行变化
newcol = col + movcol[mode];//列变化
if(newrow < 0 || newcol < 0 || newrow >= matrixSize || newcol >= matrixColSize[0] || matrix[newrow][newcol] == 1)
//如果发现下一步的探索仍有出界或者已经读取过应该退出循环了
{
break;
}
}
row = newrow;//行变化
col = newcol;//列变化
}
return returnnum;//返回一维数组
}
}
力扣59螺旋矩阵2
题目描述
思想
这题和上一题比较类似,关键步骤都一样,就是细节处理,前面不一样。可以自行体会
代码
int movrow[4]={0,1,0,-1};
int movcol[4]={1,0,-1,0};
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
{
*returnSize = n;
int **returnmat = (int**)malloc(sizeof(int*)*n);
*returnColumnSizes = (int*)malloc(sizeof(int)*n);
int i;
for(i = 0; i < n; i++)
{
returnmat[i] = (int*)malloc(sizeof(int)*n);
memset(returnmat[i],0,sizeof(int)*n);
(*returnmat)[i] = n;
}
int mode = 0;
int row = 0;
int col = 0;
int index = 1;
while(1)
{
returnmat[row][col] = index++;
int newrow = row + movrow[mode];
int newcol = col + movcol[mode];
if(newrow < 0 || newcol < 0 || newrow >= n || newcol >= n || returnmat[newrow][newcol] != 0)
{
mode = (mode + 1) % 4;
newrow = row + movrow[mode];
newcol = col + movcol[mode];
if(newrow < 0 || newcol < 0 || newrow >= n || newcol >= n || returnmat[newrow][newcol] != 0)
{
break;
}
}
row = newrow;
col = newcol;
}
return returnmat;
}