顺时针打印矩阵

#include<iostream>
#include <iomanip>
using namespace std;
#define nr 10 //定义矩阵的行和列
#define nl 7
void main()
{
    int a1[nr][nl];
    int num = 0;
    for (int i=0;i<nr;i++)
    {
        for (int j=0; j<nl; j++)
        {
            a1[i][j] = num++;
        }
    }

    for (int i=0;i<nr;i++)
    {
        for (int j=0; j<nl; j++)
        {
            cout<<setw(2)<<a1[i][j]<<" ";
        }
        cout<<endl;
    }

    int row = nr; //行
    int col = nl; //列
    int oushuda=0;
    int m,n;
    if (1 == (row & 0x1))
    {
        m=(row+1)/2;

    }
    else
    {
        m=row/2;
        oushuda = row-col;

    }
    if (1 == (col & 0x1))
    {
        n=(col+1)/2;

    }
    else
    {
        n=col/2;
        oushuda = col-row;
    }

    if (0 == row || 0 == col)
    {
        cout<<"空矩阵"<<endl;
        return;
    }
    for (int i=0,j=0; i<m&&j<n; i++,j++)
    {

        if (1==row||1==col) //如果只有一行或者一列 直接打印
        {
            for (int ii=0;ii<row;ii++)
                for(int jj=0;jj<col;jj++)
                    cout<<a1[ii][jj]<<" ";
            cout<<endl;
            break;

        }

        if ((i==m-1||j==n-1) && (row & 0x1 || col & 0x1) && oushuda>=0) //如果行和列中有奇数, 并且如果有偶数时,偶数比奇数大
        {
            if (row == col ) //如果都是奇数
            {
                cout<<a1[i][j];
                break;
            }
            else if (row>col) //如果行数大于列数
            {
                for(int m=i;m<row-i;m++)
                    cout<<a1[m][j]<<" ";
                cout<<endl;
                break;
            }else //如果列数大于行数
            {
                for(int m=j;m<col-j;m++)
                    cout<<a1[i][m]<<" ";
                cout<<endl;
                break;
            }

        }
        for (int x=j; x<col-j-1;x++) //最后一圈之前,正常打印
        {
            cout<<a1[i][x]<<" ";
        }
        cout<<endl;
        for (int x=i; x<row-i-1;x++)
        {
            cout<<a1[x][col-j-1]<<" ";
        }
        cout<<endl;
        for (int x=col-1-j; x>j;x--)
        {
            cout<<a1[row-i-1][x]<<" ";
        }
        cout<<endl;
        for (int x=row-1-i; x>i;x--)
        {
            cout<<a1[x][j]<<" ";
        }
        cout<<endl;
    }

    getchar();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值