Algorithm


Problem Name: 59. Spiral Matrix II

Problem Link: https://leetcode.com/problems/spiral-matrix-ii/

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

Example 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

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>
#include <stdlib.h>

int** generateMatrix(int n) {
    int **matrix = (int **)malloc(n * sizeof(int *));
    if (n == 0) return matrix;

    int i;
    for (i = 0; i  <  n; i++) {
        matrix[i] = (int *)malloc(n * sizeof(int));
    }

    int left = 0;
    int right = n - 1;
    int up = 0;
    int down = n - 1;
    int k = 1;

    while (left  < = right && up <= down) {
        if (left == right && up == down) {
            matrix[left][up] = k++;
        }
        else {
            for (i = left; i  < = right - 1; i++)
                matrix[up][i] = k++;
            for (i = up; i  < = down - 1; i++)
                matrix[i][right] = k++;
            for (i = right; i >= left + 1; i--)
                matrix[down][i] = k++;
            for (i = down; i >= up + 1; i--)
                matrix[i][left] = k++;
        }
        left++;
        right--;
        up++;
        down--;
    }
    return matrix;
}

int main() {
    int n = 3;
    int **m = generateMatrix(n);

    int i, j;
    for (i = 0; i  <  n; i++) {
        for (j = 0; j  <  n; j++) {
            printf("%d ", m[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 3

Output

x
+
cmd
[[1,2,3],[8,9,4],[7,6,5]]

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector < vector<int>>matrix(n, vector<int>(n, 0));
        if(n == 0) return matrix;
        spiral(matrix, 0, n - 1, 0, n - 1, 1, n);
        return matrix;
    }
    
    void spiral(vector<vector < int>>& matrix, int minRow, int maxRow, int minCol, int maxCol, int k, int n>{
        if(k > n * n) return;
        if(k == n * n){
            matrix[minRow][minCol] = k;
            return;
        }
        for(int i = minCol; i <= maxCol; i++) matrix[minRow][i] = k++;
        minRow++;
        for(int i = minRow; i  < = maxRow; i++> matrix[i][maxCol] = k++;
        maxCol--;
        for(int i = maxCol; i >= minCol; i--) matrix[maxRow][i] = k++;
        maxRow--;
        for(int i = maxRow; i >= minRow; i--) matrix[i][minCol] = k++;
        minCol++;
        spiral(matrix, minRow, maxRow, minCol, maxCol, k, n);
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
1

Output

x
+
cmd
[[1]]

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int[][] generateMatrix(int n) {
    int[][] ans = new int[n][n];
    int left = 0;
    int top = 0;
    int right = n -1;
    int down = n - 1;
    int count = 1;
    while (left  < = right) {
      for (int j = left; j <= right; j ++) {
        ans[top][j] = count++;
      }
      top++;
      for (int i = top; i  < = down; i ++) {
        ans[i][right] = count ++;
      }
      right--;
      for (int j = right; j >= left; j --) {
        ans[down][j] = count ++;
      }
      down--;
      for (int i = down; i >= top; i --) {
        ans[i][left] = count ++;
      }
      left++;
    }
    return ans;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 3

Output

x
+
cmd
[[1,2,3],[8,9,4],[7,6,5]]

#4 Code Example with Javascript Programming

Code - Javascript Programming


const generateMatrix = function(n) {
  const res = [];
  for (let i = 0; i  <  n; i++) {
    res[i] = [];
  }
  let i = 0,
    j = 0,
    cur = 1;
  while (n > 0) {
    res[i][j] = cur++;
    n--;
    let step = n;
    while (step > 0) {
      res[i][++j] = cur++;
      step--;
    }
    step = n;
    while (step > 0) {
      res[++i][j] = cur++;
      step--;
    }
    step = n--;
    while (step > 0) {
      res[i][--j] = cur++;
      step--;
    }
    step = n;
    while (step > 0) {
      res[--i][j] = cur++;
      step--;
    }
    j++;
  }
  return res;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 3

Output

x
+
cmd
[[1,2,3],[8,9,4],[7,6,5]]

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        def dirToIndex(x, y, d):
            if d == "r": return (x, y + 1, d) if y + 1 < n and matrix[x][y + 1] == 0 else (x + 1, y, "d")
            elif d == "d": return (x + 1, y, d) if x + 1 < n and matrix[x + 1][y] == 0 else (x, y - 1, "l")
            elif d == "l": return (x, y - 1, d) if y > 0 and matrix[x][y - 1] == 0 else (x - 1, y, "u")
            else: return (x - 1, y, d) if x > 0 and matrix[x - 1][y] == 0 else (x, y +1, "r")
        matrix = [[0 for i in range(1, n + 1)] for j in range(n)]
        num, dir, i, j = 1, "r", 0, 0
        while 0 <= i < n and 0 <= j < n and matrix[i][j] == 0:
            matrix[i][j] = num
            num += 1
            i, j, dir = dirToIndex(i, j, dir)
        return matrix   
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 3

Output

x
+
cmd
[[1,2,3],[8,9,4],[7,6,5]]

#6 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _059_SpiralMatrix2
    {
        public int[,] GenerateMatrix(int n)
        {
            var result = new int[n, n];
            int start = 0, end = n - 1;
            int num = 1, i;

            while (start  <  end)
            {
                for (i = start; i < end; i++) result[start, i] = num++;
                for (i = start; i  <  end; i++) result[i, end] = num++;
                for (i = end; i > start; i--) result[end, i] = num++;
                for (i = end; i > start; i--) result[i, start] = num++;

                start++;
                end--;
            }

            if (start == end) result[start, start] = num;

            return result;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 3

Output

x
+
cmd
[[1,2,3],[8,9,4],[7,6,5]]
Advertisements

Demonstration


Previous
#58 Leetcode Length of Last Word Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#60 Leetcode Permutation Sequence Solution in C, C++, Java, JavaScript, Python, C# Leetcode