lintcode-medium-Spiral Matrix
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Spiral Matrix相关的知识,希望对你有一定的参考价值。
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
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 class Solution { /** * @param matrix a matrix of m x n elements * @return an integer list */ public List<Integer> spiralOrder(int[][] matrix) { // Write your code here List<Integer> res = new ArrayList<Integer>(); if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res; int m = matrix.length; int n = matrix[0].length; int layer = 0; while((layer < m - layer - 1) && (layer < n - 1 - layer)){ for(int i = 0; i < n - layer - 1 - layer; i++) res.add(matrix[layer][layer + i]); for(int i = 0; i < m - layer - 1 - layer; i++) res.add(matrix[layer + i][n - layer - 1]); for(int i = 0; i < n - layer - 1 - layer; i++) res.add(matrix[m - layer - 1][n - layer - 1 - i]); for(int i = 0; i < m - layer - 1 - layer; i++) res.add(matrix[m - layer - 1 - i][layer]); layer++; } if(m > n){ if(layer == n - 1 - layer){ for(int i = layer; i <= m - layer - 1; i++) res.add(matrix[i][layer]); } } else if(m < n){ if(layer == m - 1 - layer){ for(int i = layer; i <= n - layer - 1; i++) res.add(matrix[layer][i]); } } else{ if(layer == m - 1 - layer){ res.add(matrix[layer][layer]); } } return res; } }
以上是关于lintcode-medium-Spiral Matrix的主要内容,如果未能解决你的问题,请参考以下文章