用c语言写一个螺旋矩阵
时间: 2024-05-21 17:13:13 浏览: 8
下面是一个用C语言实现的螺旋矩阵的代码示例:
#include <stdio.h>
void printSpiralMatrix(int rows, int cols, int matrix[][cols]) {
int startRow = 0, endRow = rows - 1;
int startCol = 0, endCol = cols - 1;
while (startRow <= endRow && startCol <= endCol) {
// 打印上行
for (int j = startCol; j <= endCol; j++) {
printf("%d ", matrix[startRow][j]);
}
startRow++;
// 打印右列
for (int i = startRow; i <= endRow; i++) {
printf("%d ", matrix[i][endCol]);
}
endCol--;
// 打印下行
if (startRow <= endRow) {
for (int j = endCol; j >= startCol; j--) {
printf("%d ", matrix[endRow][j]);
}
endRow--;
}
// 打印左列
if (startCol <= endCol) {
for (int i = endRow; i >= startRow; i--) {
printf("%d ", matrix[i][startCol]);
}
startCol++;
}
}
}
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printSpiralMatrix(3, 3, matrix);
return 0;
}
输出结果为:1 2 3 6 9 8 7 4 5
希望能帮助到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)