from:http://blog.csdn.net/zhoujunbuaa/article/details/6121375
题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:如果输入如下矩阵:
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。
网上听说听到包括Autodesk、EMC在内的多家公司在面试或者笔试里采用过这道题。但是看有些人做的,头晕。还是自己弄了弄。
解题思路(借鉴 迷宫问题):1)在矩阵周围 添加一堵墙 (-1);
2)分为四个方向运动,向右,向下,向左,向右。
3)在碰到墙 或者 已经走过的点, 则改变方向,方向的改变依赖上条的四个方向,依次循环找下一个方向。(而具体方向的执行,表现在 下标的改动)。
4)用printCount计数打印了的点数,也就是 走过的路径长度,而总路径长度是size*size的,如果大于它了,则不需要在往下执行
- // ClockWisePrintMatrix_顺时针打印矩阵.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #define MAX_SIZE 100
- int Matrix[MAX_SIZE][MAX_SIZE];
- int size;
- #define START_X 1
- #define START_Y 0
- int END_X,END_Y;
- typedef enum Direction{
- RIGHT=0,
- DOWN=1,
- LEFT=2,
- UP=3,
- };
- //wall is -1, if has walked also change value to -1
- void BuildOutsideWall()
- {
- for(int i=0;i<size+2;i++)
- {
- Matrix[0][i]=-1;
- Matrix[size+1][i]=-1;
- }
- for(int i=1;i<size+2;i++)
- {
- Matrix[i][0]=-1;
- Matrix[i][size+1]=-1;
- }
- }
- Direction ChangeDirection(int dir)
- {
- switch (dir)
- {
- case RIGHT:
- return DOWN;
- case DOWN:
- return LEFT;
- case LEFT:
- return UP;
- case UP:
- return RIGHT;
- }
- }
- void PrintClockWiseMatrix()
- {
- int i=START_X,j=START_Y;
- Direction dir=RIGHT;
- int printCount=0;
- while(printCount<=size*size)
- {
- switch(dir)
- {
- case RIGHT:
- if(Matrix[i][j+1]!=-1)
- {
- j++;
- printf("%d ",Matrix[i][j]);
- Matrix[i][j]=-1;
- printCount++;
- }
- else
- {
- dir=ChangeDirection(dir);
- }
- break;
- case DOWN:
- if(Matrix[i+1][j]!=-1)
- {
- i++;
- printf("%d ",Matrix[i][j]);
- Matrix[i][j]=-1;
- printCount++;
- }
- else
- {
- dir=ChangeDirection(dir);
- }
- break;
- case LEFT:
- if(Matrix[i][j-1]!=-1)
- {
- j--;
- printf("%d ",Matrix[i][j]);
- Matrix[i][j]=-1;
- printCount++;
- }
- else
- {
- dir=ChangeDirection(dir);
- }
- break;
- case UP:
- if(Matrix[i-1][j]!=-1)
- {
- i--;
- printf("%d ",Matrix[i][j]);
- Matrix[i][j]=-1;
- printCount++;
- }
- else
- {
- dir=ChangeDirection(dir);
- }
- break;
- }
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- scanf("%d",&size);
- END_X=END_Y=size;
- BuildOutsideWall();
- for(int i=1;i<=size;i++)
- for(int j=1;j<=size;j++)
- {
- scanf("%d",&Matrix[i][j]);
- }
- PrintClockWiseMatrix();
- return 0;
- }
1、这是在假定输入的矩阵不会出现-1情况下,如果说可以出现任何数,我们可以添加其他逻辑进行控制,原理是一样的。例如添加一个bool数组标记矩阵的每一个点的走过状态。
2、假如不可以 添加围墙,那么我们可以检测 边界,即检测当前打印如果是 角点,那么换方向。