题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.
思路
最单纯的思路就是,定义一个枚举来表示上下左右四个方向,再定义一个数组来记录已经遍历过的位置。最后通过while循环和switch解题
代码
using System.Collections.Generic;
public enum Direc
{
right,down,left,up
}
class Solution
{
public List<int> printMatrix(int[][] matrix)
{
// write code here
// write code here
List<int> list = new List<int>();
int length1 = matrix.Length,length2=matrix[0].Length;
int length = length1 * length2;
int[,] a = new int[length1, length2];
int num = 0,direcNum=0,rIndex=0,cIndex=0;
Direc dic;
while(num <length)
{
dic = (Direc)direcNum;
switch (dic)
{
case Direc.right:
if (rIndex >= length1 || cIndex >= length2 || rIndex < 0 || cIndex < 0 || a[rIndex, cIndex] == 1)
{
direcNum++;
rIndex++;
cIndex--;
break;
}
list.Add(matrix[rIndex][cIndex]);
a[rIndex, cIndex] = 1;
cIndex++;
num++;
break;
case Direc.down:
if (rIndex >= length1 || cIndex >= length2 || rIndex < 0 || cIndex < 0 || a[rIndex, cIndex] == 1)
{
direcNum++;
rIndex--;
cIndex--;
break;
}
list.Add(matrix[rIndex][cIndex]);
a[rIndex, cIndex] = 1;
rIndex++;
num++;
break;
case Direc.left:
if (rIndex >= length1 || cIndex >= length2 || rIndex < 0 || cIndex < 0 || a[rIndex, cIndex] == 1)
{
direcNum++;
rIndex--;
cIndex++;
break;
}
list.Add(matrix[rIndex][cIndex]);
a[rIndex, cIndex] = 1;
cIndex--;
num++;
break;
case Direc.up:
if (rIndex >= length1 || cIndex >= length2 || rIndex < 0 || cIndex < 0 || a[rIndex, cIndex] == 1)
{
direcNum=0;
rIndex++;
cIndex++;
break;
}
list.Add(matrix[rIndex][cIndex]);
a[rIndex, cIndex] = 1;
rIndex--;
num++;
break;
}
}
return list;
}
}