Skip to content

Latest commit

 

History

History
64 lines (52 loc) · 1.39 KB

59. Spiral Matrix II.md

File metadata and controls

64 lines (52 loc) · 1.39 KB

leetcode Daily Challenge on December 7th, 2020.


Difficulty : Medium

Related Topics : Array


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

Example 1:

1

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20

Solution

  • 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;
        }