C语言题解
2025-07-05 08:58:06
发布于:浙江
4阅读
0回复
0点赞
#include <stdio.h>
#include <stdlib.h>
void snake(int n,int m,int I,int J){
int **matrix = (int **)malloc(n * sizeof(int *));
for (int i = 0; i < n; i++) {
matrix[i] = (int *)malloc(m * sizeof(int));
}
int top = 0, bottom = n - 1, left = 0, right = m - 1;
int num = 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
top++;
for (int i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
}
}
printf("%d",matrix[I-1][J-1]);
for (int i = 0; i < n; i++) {
free(matrix[i]);
}
free(matrix);
}
int main(void){
int n,i,j;
scanf("%d%d%d",&n,&i,&j);
snake(n,n,i,j);
return 0;
}
这里空空如也
有帮助,赞一个