虎牙安卓笔试:矩阵逆时针输出

参考博客:https://blog.csdn.net/jjjcainiao/article/details/23384447

将矩阵分层,总共可以形成 min(m / 2, n / 2)层。

每层分为左、下、右、上四边,按左下右上顺序循环输出各层。

若min(m , n)为奇数,最后还有一部分不能构成层,需要特别处理。

原来这题还是金山的笔试题(灬ꈍ ꈍ灬)

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

int main()
{
    int i, j;
    int n, m;
    cin >> n >> m;
    int **matrix=(int **)malloc(n * sizeof(int *)); 
    for(i=0; i<n; i++)
        matrix[i]=(int *)malloc(m * sizeof(int));
    for(i=0; i<n; i++)   
        for(j=0; j<m; j++)
            cin >> matrix[i][j];
    for(i=0; i<m/2; i++)
    {
        for(j=i; j< n-i; j++){
			cout<<matrix[j][i];
        	cout<<" ";
		}  
        
        for(j = i + 1; j < m - i - 1; j++){
			cout<<matrix[n - i - 1][j];
	        cout<<" ";
		}  
        	
        for(j = n - i - 1; j >= i; j--){
			cout<<matrix[j][m - i - 1];
        	cout<<" ";
		}  
        	
        for(j = m - i - 2; j > i; j--){
			cout<<matrix[i][j];
        	cout<<" ";
		}  

    }
    if(m <= n && (m % 2 == 1))   
        for(i = 0; i <= n - m; i++){
        	cout <<  matrix[m / 2 + i][m / 2];
        	cout<<" ";
        }
        	
    else if(m > n && (n % 2 == 1))
        for(i = 0; i <= m - n; i++){
        	cout<<matrix[n / 2][n / 2 + i];
        	cout<<" ";
        }
        	
    cout<<endl;
    for(i = 0; i < n; i++)  
        free(matrix[i]);
    free(matrix);
}

猜你喜欢

转载自blog.csdn.net/cyanchen666/article/details/82469091
今日推荐