54. Spiral Matrix

来源:互联网 发布:android 开启数据连接 编辑:程序博客网 时间:2024/06/07 06:09

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

Subscribe to see which companies asked this question.

public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> re = new ArrayList<Integer>();if (matrix == null || matrix.length == 0)return re;int m = matrix.length;int n = matrix[0].length;int up = 0;int down = m - 1;int left = 0;int right = n - 1;int i = 0;int posi = 0;int posj = 0;int sum = m * n;while (i < sum) {while (posj <= right) {re.add(matrix[posi][posj]);posj++;i++;}if (i == sum)break;up++;posj--;posi++;while (posi <= down) {re.add(matrix[posi][posj]);posi++;i++;}if (i == sum)break;right--;posi--;posj--;while (posj >= left) {re.add(matrix[posi][posj]);posj--;i++;}if (i == sum)break;down--;posj++;posi--;while (posi >= up) {re.add(matrix[posi][posj]);posi--;i++;}left++;posi++;posj++;}return re;    }}


0 0
原创粉丝点击