面试题20:顺时针打印矩阵

来源:互联网 发布:知困然后能自强也 编辑:程序博客网 时间:2024/05/14 07:01

题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

例如      则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10


思路:可以看做不断打印几个依次缩小的圆圈。第一个圆圈的起点是(1,1),第二个是(2,2),依次类推。

int main(int argc, const char * argv[]) {    int a[][4] = {1, 2, 3, 4,                  5, 6, 7, 8,                  9, 10,11,12,                  13,14,15,16,                  17,18,19,20,                  21,22,23,24};        int row = 6;    int col = 4;    //➡️ ⬇️ ⬅️ ⬆️    int start = 0;            while(col>start*2 && row>start*2)    {        int endX = col - start;        int endY = row - start;        int x = start;        int y = start;        while(endX > 0 && x < endX)        {            cout<<a[y][x]<<" ";            x++;        }        x--;        y++;                while(endY > 0 && y < endY)        {            cout<<a[y][x]<<" ";            y++;        }        y--;        x--;                while(x >= start)        {            cout<<a[y][x]<<" ";            x--;        }        x++;        y--;                        while(y > start)        {            cout<<a[y][x]<<" ";            y--;        }        y++;        x++;                start++;            }        cout<<endl;                    return 0;}


0 0
原创粉丝点击