java常用算法之螺旋矩阵

给定一个m*n矩阵,返回所有元素在矩阵中的螺旋序列,例如:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

返回[1,2,3,6,9,8,7,4,5].

算法实现如下:

public static List<Integer> spiralMatrix(int source[][]) {
		List<Integer> result = new ArrayList();
		int columns = source[0].length;
		int rows = source.length;
		int m = 0;
		int length = rows * columns;
		while (result.size() < length) {
			for (int i = m; i < columns; i++) {
				result.add(source[m][i]);
			}
			if (result.size() == length) {
				break;
			}
			for (int i = m + 1; i < rows; i++) {
				result.add(source[i][columns - 1]);
			}
			if (result.size() == length) {
				break;
			}
			for (int i = columns - 2; i > (m - 1); i--) {
				result.add(source[rows - 1][i]);
			}
			if (result.size() == length) {
				break;
			}
			for (int i = rows - 2; i > m; i--) {
				result.add(source[i][m]);
			}
			m++;
			columns = columns - 1;
			rows = rows - 1;
		}
		return result;
	}

	public static void main(String[] args) {
		int a[][] = { { 1, 3, 5, 6 }, { 10, 7, 8, 2 }, { 9, 12, 11, 13 },
				{ 17, 19, 21, 22 }, { 31, 32, 35, 37 } };
		List<Integer> result = spiralMatrix(a);
		System.err.println(result.toString());
	}


输出结果:

[1, 3, 5, 6, 2, 13, 22, 37, 35, 32, 31, 17, 9, 10, 7, 8, 11, 21, 19, 12]


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值