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].
代码分析:
就是Amazon电面我的题,当时弱爆的我只是瞎写一通。虽然现在还是弱爆,但是,应该能跌跌撞撞写出来。
两个corner case. 只有一行,只有一列。
分四部分打印一个环。上行,右列,下行,左列,打印下行,左列的时候要判断还有没有东西,不然会重复打印了上行和右列。
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. 只有一行,只有一列。
分四部分打印一个环。上行,右列,下行,左列,打印下行,左列的时候要判断还有没有东西,不然会重复打印了上行和右列。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Subsets II
- LeetCode Online Judge 题目C# 练习 - Edit Distance
- LeetCode Online Judge 题目C# 练习 - Word Search
- LeetCode Online Judge 题目C# 练习 - Binary Tree Inorder Traversal
- LeetCode Online Judge 题目C# 练习 - Gray Code
- LeetCode Online Judge 题目C# 练习 - ZigZag Conversion
- LeetCode Online Judge 题目C# 练习 - Implement strStr()
- LeetCode Online Judge 题目C# 练习 - Longest Substring Without Repeating Characters
- LeetCode Online Judge 题目C# 练习 - Reverse Nodes in k-Group
- LeetCode Online Judge 题目C# 练习 - Add two number
- LeetCode Online Judge 题目C# 练习 - 4SUM
- LeetCode Online Judge 题目C# 练习 - Binary Tree Level Order Traversal II
- LeetCode Online Judge 题目C# 练习 - Combination
- LeetCode Online Judge 题目C# 练习 - N-Queens
- LeetCode Online Judge 题目C# 练习 - Length of Last Word
- LeetCode Online Judge 题目C# 练习 - Add Binary
- LeetCode Online Judge 题目C# 练习 - Two Sum
- LeetCode Online Judge 题目C# 练习 - Count and Say
- LeetCode Online Judge 题目C# 练习 - Minimum Window Substring
- LeetCode Online Judge 题目C# 练习 - Remove Element