leetcode Daily Challenge on December 7th, 2020.
Difficulty : Medium
Related Topics : Array
Given a positive integer
n
, generate ann x n
matrix
filled with elements from1
ton^2
in spiral order.Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
Input: n = 1 Output: [[1]]
1 <= n <= 20
- mine
- Java
Runtime: 0 ms, faster than 100.00%, Memory Usage: 38.4 MB, less than 5.05% of Java online submissions
public int[][] generateMatrix(int n) { int[][] arr = {{0,1},{1,0},{0,-1},{-1,0}}; int index = 0; int total = n * n; int x = 0, y = 0; int[][] res = new int[n][n]; for(int i = 1; i <= total; i++){ res[x][y] = i; int nextx = x + arr[index][0]; int nexty = y + arr[index][1]; if(nextx < 0 || nextx >= n || nexty < 0 || nexty >= n || res[nextx][nexty] != 0){ index = (index + 1) % 4; } x += arr[index][0]; y += arr[index][1]; } return res; }
- Java