TypechoJoeTheme

IT技术分享

统计

[LeetCode 59] Spiral Matrix II [Java]

2018-01-31
/
0 评论
/
618 阅读
/
正在检测是否收录...
01/31

1. Description

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

2. Example

Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

3. Code

import java.util.Arrays;

public class LeetCode0059 {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int firstRow = 0, lastRow = n - 1, firstCol = 0, lastCol = n - 1;

        int num = 1;
        while (num <= n * n) {
            for (int j = firstCol; j <= lastCol; j++) {
                result[firstRow][j] = num++;
            }
            firstRow++;
            for (int i = firstRow; i <= lastRow; i++) {
                result[i][lastCol] = num++;
            }
            lastCol--;
            for (int j = lastCol; j >= firstCol; j--) {
                result[lastRow][j] = num++;
            }
            lastRow--;
            for (int i = lastRow; i >= firstRow; i--) {
                result[i][firstCol] = num++;
            }
            firstCol++;
        }
        return result;
    }

    public static void main(String[] args) {
        LeetCode0059 leetcode = new LeetCode0059();
        int n = 3;
        int[][] result = leetcode.generateMatrix(n);
        for (int i = 0; i < n; i++) {
            System.out.println(Arrays.toString(result[i]));
        }
    }
}
Matrix
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1419/(转载时请注明本文出处及文章链接)