剑指offer——输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如,输入如下矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10。
分析:把矩阵看成若干个圈。利用循环一次打印一个圈。假如矩阵有ROW行,COL列,选取左上角坐标为(start,start)的点开始打印,对于一个5*5的矩阵,最后一圈坐标为(2,2),对于6*6的矩阵,最后一圈坐标也是(2,2)。因此,由规律可知,循环继续的条件是:COL>start*2并且ROW>start*2。
打印一圈:分为四步。不过要考虑最后一行有可能退化成一行,一列,或者一个数字。这样就不是每一圈都能走完四步,因此需要进行判断。
- 从左到右打印一行
- 从上到下打印一行:(前提条件)endy > start 终止行号大于起始行号
- 从右到左打印一行:(前提条件)endx > start && endy > start 终止行号大于起始行号并且终止列号大于起始列号
- 从下到上打印一行:(前提条件) endx + 2> endy && endy > start 终止行号比起始行号大2并且终止列号大于起始列号
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#define ROW 5
#define COL 4
void show(int(*a)[COL], int row, int col)
{
int i = 0;
int j = 0;
for (; i < row; i++){
for (j = 0; j < col; j++){
printf("%2d ", a[i][j]);
}
printf("\n");
}
return;
}
void PrintCircle(int(*a)[COL], int row, int col, int start)
{
int endx = col - 1 - start;
int endy = row - 1 - start;
//从左到右
for (int j = start; j <= endx; j++){
printf("%d ", a[start][j]);
}
//从上到下
if (endy > start){
for (int i = start + 1; i <= endy; i++){
printf("%d ", a[i][endx]);
}
}
//从右到左
if (endx > start && endy > start){
for (int j = endx - 1; j >= start; j--){
printf("%d ", a[endy][j]);
}
}
//从下到上
if ((endx + 2) > endy && endy > start){
for (int i = endy - 1; i >= start + 1; i--){
printf("%d ", a[i][start]);
}
}
return;
}
void Print(int(*a)[COL], int row, int col)
{
int start = 0;
if (a == NULL || row <= 0 || col <= 0){
return;
}
while (start * 2 < row && start * 2 < col){
PrintCircle(a, row, col, start);
start++;
}
return;
}
int main()
{
int a[ROW][COL] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
show(a, ROW, COL);
Print(a, ROW, COL);
printf("\n");
system("pause");
return 0;
}