LeetCode059——螺旋矩阵II

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/spiral-matrix-ii/description/

题目描述:

LeetCode059——螺旋矩阵II_第1张图片

知识点:数组

思路:实时更新螺旋的四个边界left、right、top、bottom的值

本题的思路和LeetCode054——螺旋矩阵的思路二一模一样,因此不再过多分析。

JAVA代码:

public class Solution {

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

LeetCode解题报告:

LeetCode059——螺旋矩阵II_第2张图片

 

你可能感兴趣的:(LeetCode题解)