Description:
-
Enter a matrix and print each number in clockwise order from the external, for example, if you enter the following matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The numbers 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 are printed in sequence.
-
Input:
-
The input may contain multiple test examples. For each test case,
The first line of the input contains two integers m and n (1 <= m, n <= 1000): the dimension of the matrix is m rows and n columns.
In the next m row, each row contains n integers, indicating the elements of the matrix. The value range of each element a is (1 <= a <= 10000 ).
-
Output:
-
Output a line for each test case,
Each number is printed in clockwise order from the forward to the right, and each number is followed by a space.
-
Sample input:
-
4 41 2 3 45 6 7 89 10 11 1213 14 15 16
-
Sample output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Solution:
This questionThere is a pitfall, but it has been explained in the question that every number is followed by a space. Therefore, the last number also has a space..
The main idea is to adopt a layer-by-layer strip output. We mark the range of threshold_m and threshold_n in each row, and then call the output function by specifying the output vertex.
threshold_n = n; threshold_m = m; i=0; j=0; while(i<threshold_m && j < threshold_n){ printMatrix(i,j); i++; j++; threshold_n--; threshold_m--; }
void printMatrix(int m,int n){ int i=m,j=n; for( ;j<threshold_n;j++){ printf("%d ",arr[i][j]); } j--; for(i++;i<threshold_m;i++){ printf("%d ",arr[i][j]); } i--; for(j--;j>=n && i!=m;j--){ printf("%d ",arr[i][j]); } j++; for(i--;i>m && j!=threshold_n-1;i--){ printf("%d ",arr[i][j]); }}
All code:
#include <stdio.h>#define MAXSIZE 1000int arr[MAXSIZE][MAXSIZE] = {0};int threshold_m = 0;int threshold_n = 0;void printMatrix(int m,int n); int main(){ int m,n,i,j; while(scanf("%d %d",&m,&n) != EOF && n>=1 && n<=1000 && m>=1 && m<=1000){ for(i=0; i<m; i++){ for(j=0; j<n; j++) scanf("%d",&arr[i][j]); } threshold_n = n; threshold_m = m; i=0; j=0; while(i<threshold_m && j < threshold_n){ printMatrix(i,j); i++; j++; threshold_n--; threshold_m--; } printf("\n"); } return 0;}void printMatrix(int m,int n){ int i=m,j=n; for( ;j<threshold_n;j++){ printf("%d ",arr[i][j]); } j--; for(i++;i<threshold_m;i++){ printf("%d ",arr[i][j]); } i--; for(j--;j>=n && i!=m;j--){ printf("%d ",arr[i][j]); } j++; for(i--;i>m && j!=threshold_n-1;i--){ printf("%d ",arr[i][j]); }}/************************************************************** Problem: 1391 User: xhalo Language: C Result: Accepted Time:560 ms Memory:4820 kb****************************************************************/
-