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 ] ]
Subscribe to see which companies asked this question
分析:首先依次遍历路径,每走一步在上一步的值上加1.类似的题目是leetcode93还有腾讯笔试的编程题目。
/** * 首先依次遍历路径,每走一步在上一步的值上加1. * @date 构造蛇形矩阵。 */ public int[][] generateMatrix(int n) { int index = 1; int[][] matrix = new int[n][n]; int rows = n;/*记录矩阵的行数 */ int cols = n;/*记录矩阵的列数 */ int start = 0; /* 每次找出矩阵中最外面还没有被找到的那一圈元素,每一圈的开始坐标是(start,start) */ while (start * 2 < rows && start * 2 < cols) { int endRow = rows - 1 - start; // 每一圈的结束行坐标 int endCol = cols - 1 - start; /* 第一步打印:从左到右,行坐标start不变,列坐标由start到endCol */ for (int j = start; j <= endCol; j++) { matrix[start][j] = index; index++; } if (endRow > start) {/* 第二步打印:从上到下,行坐标由start+1到endRow-1,列左边endCol不变 */ for (int i = start + 1; i <= endRow; i++) { matrix[i][endCol] = index; index++; } } if (endRow > start && endCol > start) { /* * 第三步打印:从右到左,行坐标endRow不变, * 列坐标由endCol-1到start */ for (int j = endCol - 1; j >= start; j--) { matrix[endRow][j] = index; index++; } } if (endRow > start + 1 && endCol > start) { /* * 第四步打印:从下到上,行坐标由endRow- * 1到start+1,列坐标start不变 */ for (int i = endRow - 1; i >= start + 1; i--) { matrix[i][start] = index; index++; } } start++; } return matrix; }