面试题20顺时针打印矩阵

来源:互联网 发布:wifi和数据同时开 编辑:程序博客网 时间:2024/05/16 23:40

地址:http://ac.jobdu.com/problem.php?pid=1391

题目1391:顺时针打印矩阵

题目描述:

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

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.

输入:

输入可能包含多个测试样例,对于每个测试案例,

输入的第一行包括两个整数m和n(1<=m,n<=1000):表示矩阵的维数为m行n列。

接下来的m行,每行包括n个整数,表示矩阵的元素,其中每个元素a的取值范围为(1<=a<=10000)。

输出:

对应每个测试案例,输出一行,

按照从外向里以顺时针的顺序依次打印出每一个数字,每个数字后面都有一个空格。

样例输入:
4 41 2 3 45 6 7 89 10 11 1213 14 15 16
样例输出:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 
答疑:
解题遇到问题?分享解题心得?讨论本题请访问:http://t.jobdu.com/thread-8114-1-1.html

解题思路:

1、以矩阵左上角为起点进行打印

2、继续打印下一圈的条件:

column > start * 2 && row > start * 2

column 为矩阵的列数,row 为矩阵的行数,start 为矩阵左上角的行(列)数(例如:第0行第0列, 第2行第2列)

2、打印一圈分为4步:

(1)从左到右

(2)从上到下:至少两行

(3)从右到左:至少两行两列

(4)从下到上:至少三行两列

#include <stdio.h>#include <stdlib.h>void printMatrixInCircle(int **numbers, int columns, int rows, int start){    int rightColumn = columns - start - 1;    int bottonLine = rows - start - 1;     for(int l = start; l <= rightColumn; l ++)    {            printf("%d ", numbers[start][l]);    }     if((bottonLine - start) >= 1)    {        for(int r = start + 1; r <= bottonLine; r ++)        {            printf("%d ", numbers[r][rightColumn]);        }    }     if((rightColumn - start) >= 1 && (bottonLine - start) >= 1)    {        for(int l = rightColumn - 1; l >= start; l --)        {            printf("%d ", numbers[bottonLine][l]);        }    }     if((bottonLine - start) >= 2 && (rightColumn - start) >= 1)    {        for(int r = bottonLine - 1; r > start; r --)        {            printf("%d ", numbers[r][start]);        }    }}void printMatrixClockWisely(int **numbers, int columns, int rows){    if(numbers == NULL || columns <= 0 || rows <=0)        return;    int start = 0;    while(rows > start * 2 && columns > start * 2)    {        printMatrixInCircle(numbers, columns, rows, start);        start ++;    }}int main(){    int m, n;    while(scanf("%d %d", &m, &n) != EOF)    {        int **numbers = (int **)malloc(sizeof(int *) * m);        for(int i = 0; i < m; i ++)        {            numbers[i] = (int *)malloc(sizeof(int) * n);        }        for(int i = 0; i < m; i ++)        {            for(int j = 0; j < n; j ++)            {                scanf("%d", &numbers[i][j]);            }        }        printMatrixClockWisely(numbers, n, m);        printf("\n");    }    return 0;}/**************************************************************    Problem: 1391    Language: C++    Result: Accepted    Time:530 ms    Memory:3660 kb****************************************************************/




0 0