首页 > 其他 > 详细

LeetCode——Spiral Matrix

时间:2015-02-05 10:50:06      阅读:239      评论:0      收藏:0      [点我收藏+]

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].

原题链接:https://oj.leetcode.com/problems/spiral-matrix/

向右螺旋式遍历。


public class SpiralMatrix {
	public List<Integer> spiralOrder(int[][] matrix) {
		if (matrix.length == 0)
			return null;
		List<Integer> list = new ArrayList<Integer>();
		int l = 0, r = matrix[0].length - 1;
		int u = 0, d = matrix.length - 1;
		while (l <= r && u <= d) {
			for (int i = l; i <= r; i++)
				list.add(matrix[u][i]);
			u++;
			if (u > d)
				continue;
			for (int i = u; i <= d; i++)
				list.add(matrix[i][r]);
			r--;
			if (l > r)
				continue;
			for (int i = r; i >= l; i--)
				list.add(matrix[d][i]);
			d--;
			if (u > d)
				continue;
			for (int i = d; i >= u; i--)
				list.add(matrix[i][l]);
			l++;
		}
		return list;
	}
}


LeetCode——Spiral Matrix

原文:http://www.cnblogs.com/mengfanrong/p/4274103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!