首页 > 代码库 > LeetCode——Spiral Matrix II
LeetCode——Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]原题链接:https://oj.leetcode.com/problems/spiral-matrix-ii/
之前的一题是将螺旋结构的二维数组转成一维数组,此题正好相反,故只需将原来的位置上取下来的元素放回去。
public class SpiralMatrixII { public static void main(String[] args) { int[][] matrix = new SpiralMatrixII().generateMatrix(3); for(int[] r : matrix){ for(int c : r) System.out.print(c + "\t"); System.out.println(); } } public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; if(n == 0) return matrix; int l = 0, r = matrix[0].length - 1; int u = 0, d = matrix.length - 1; int num = 1; while (l <= r && u <= d) { for (int i = l; i <= r; i++) matrix[u][i] = num++; u++; if (u > d) continue; for (int i = u; i <= d; i++) matrix[i][r] = num++; r--; if (l > r) continue; for (int i = r; i >= l; i--) matrix[d][i] = num++; d--; if (u > d) continue; for (int i = d; i >= u; i--) matrix[i][l] = num++; l++; } return matrix; } }
LeetCode——Spiral Matrix II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。