54+59、Spiral Matrix、Spiral Matri

2018-04-18  本文已影响0人  小鲜贝

Spiral Matrix

Example

Given the following matrix:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
return [1,2,3,6,9,8,7,4,5].

思路
螺旋遍历输出一个m * n的数组。方向是上、右、下、左,依次循环。

解法

public class Solution{
    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int m = matrix.length;// rows
        if (m == 0) {
            return result;
        }
        int n = matrix[0].length;// columns
        int topOffset = 0;
        int rightOffset = 0;
        int bottomOffset = 0;
        int leftOffset = 0;
        while (true) {
            // top
            for (int i = leftOffset; i < n - rightOffset; i++) {
                result.add(matrix[topOffset][i]);
            }
            topOffset++;
            if (topOffset + bottomOffset == m) {
                break;
            }
            // right
            for (int i = topOffset; i < m - bottomOffset; i++) {
                result.add(matrix[i][n - 1 - rightOffset]);
            }
            rightOffset++;
            if (leftOffset + rightOffset == n) {
                break;
            }
            // bottom
            for (int i = n - 1 - rightOffset; i >= leftOffset; i--) {
                result.add(matrix[m - 1 - bottomOffset][i]);
            }
            bottomOffset++;
            if (topOffset + bottomOffset == m) {
                break;
            }
            // left
            for (int i = m - 1 - bottomOffset; i >= topOffset; i--) {
                result.add(matrix[i][leftOffset]);
            }
            leftOffset++;
            if (leftOffset + rightOffset == n) {
                break;
            }
        }
        return result;
    }
}

Spiral Matrix 2

Example

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

解法

public class Solution {
    public int[][] generateMatrix(int n) {
        int num = 1;
        int[][] res = new int[n][n];
        for (int cur = 0; cur < n/2; cur++) {
            for (int j = cur; j < n-1-cur; j++) {
                res[cur][j] = num++;
            }
            for (int i = cur; i < n-1-cur; i++) {
                res[i][n-1-cur] = num++;
            }
            for (int j = n-1-cur; j > cur; j--) {
                res[n-1-cur][j] = num++;
            }
            for (int i = n-1-cur; i > cur; i--) {
                res[i][cur] = num++;
            }
        }
        if (n % 2 != 0) res[n/2][n/2] = num;
        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读