【LeetCode】59. Spiral Matrix II 解题报告

来源:互联网 发布:mac 网页添加到收藏夹 编辑:程序博客网 时间:2024/06/12 01:50

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51416284


Subject

出处:https://leetcode.com/problems/spiral-matrix/

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

For example, Given n = 3,
You should return the following matrix:

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

Explain

螺旋遍历往一个n*n的数组中填入数字。方向是→、↓、←、↑,依次循环。


My Solution

使用螺旋遍历输出数组的方法,填入数字即可,数字自增。

参考:http://blog.csdn.net/crazy1235/article/details/51416037


public static int[][] generateMatrix(int n) {        int[][] result = new int[n][n];        int top = 0;        int right = 0;        int bottom = 0;        int left = 0;        int index = 1;        int i = 0;        while (true) {            // top            for (i = left; i < n - right; i++) {                result[top][i] = index++;            }            top++;            if (top + bottom == n) {                break;            }            // right            for (i = top; i < n - bottom; i++) {                result[i][n - 1 - right] = index++;            }            right++;            if (left + right == n) {                break;            }            // bottom            for (i = n - 1 - right; i >= left; i--) {                result[n - 1 - bottom][i] = index++;            }            bottom++;            if (top + bottom == n) {                break;            }            // left            for (i = n - 1 - bottom; i >= top; i--) {                result[i][left] = index++;            }            left++;            if (left + right == n) {                break;            }        }        return result;    }


由于是n * n的数组,所以只需要判断top + bottom 或者left + right即可。将判断条件放到while中。

public static int[][] generateMatrix2(int n) {        int[][] result = new int[n][n];        int topOffset = 0;        int rightOffset = 0;        int bottomOffset = 0;        int leftOffset = 0;        int index = 1;        int i = 0;        while (topOffset + bottomOffset < n) {            // top            for (i = leftOffset; i < n - rightOffset; i++) {                result[topOffset][i] = index++;            }            topOffset++;            // right            for (i = topOffset; i < n - bottomOffset; i++) {                result[i][n - 1 - rightOffset] = index++;            }            rightOffset++;            // bottom            for (i = n - 1 - rightOffset; i >= leftOffset; i--) {                result[n - 1 - bottomOffset][i] = index++;            }            bottomOffset++;            // left            for (i = n - 1 - bottomOffset; i >= topOffset; i--) {                result[i][leftOffset] = index++;            }            leftOffset++;        }        return result;    }

1 0
原创粉丝点击