您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Sprial Matrix

2012-10-17 23:04 423 查看
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

public static List<int> SprialMatrix(List<List<int>> matrix)
{
if (matrix.Count == 0)
return null;

int m = matrix.Count - 1;
int n = matrix[0].Count - 1;

List<int> ret = new List<int>();
//one row
if (m == 0)
{
return matrix[0];
}
//one column
if (n == 0)
{
for (int i = 0; i <= m; i++)
{
ret.Add(matrix[i][0]);
}
return ret;
}

for (int i = 0; i <= (Math.Min(m ,n)) / 2; i++)
{
for (int col = i; col <= n - i; col++)
{
ret.Add(matrix[i][col]);
}
for (int row = i + 1; row <= m - i; row++)
{
ret.Add(matrix[row][n - i]);
}
if (m - i > i)
{
for (int col = n - i - 1; col >= i; col--)
{
ret.Add(matrix[m - i][col]);
}
}
if (n - i > i)
{
for (int row = m - i - 1; row > i; row--)
{
ret.Add(matrix[row][i]);
}
}
}

return ret;
}


代码分析:

  就是Amazon电面我的题,当时弱爆的我只是瞎写一通。虽然现在还是弱爆,但是,应该能跌跌撞撞写出来。

  两个corner case. 只有一行,只有一列。

  分四部分打印一个环。上行,右列,下行,左列,打印下行,左列的时候要判断还有没有东西,不然会重复打印了上行和右列。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: