300th

This is my 300th leetcode problem solved: https://leetcode.com/problems/spiral-matrix-ii/description/

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

My approach is to have an outer loop going from the upper left corner towards the center of the matrix via the diagonal. This variable will control the beginning of the row/col being worked on. Inside the outer loop you will have 4 loops: left to right, top to bottom, right to left and finally bottom to top. You should also be careful to not add the corner elements twice. Call your variables "c" and "r" to facilitate the implementation (col and row). Just play with the indexes a bit, focus on the symmetry of the solution, and it should do it. Code is below - thanks, Boris.


public class Solution
{
 public int[,] GenerateMatrix(int n)
 {
  int[,] retVal = new int[n, n];

  int index = 1;

  for (int i = 0; i <= n / 2; i++)
  {
   //LR
   for (int c = i; c < n - i; c++) retVal[i, c] = index++;
   //UD
   for (int r = i + 1; r < n - i; r++) retVal[r, n - i - 1] = index++;
   //RL
   for (int c = n - i - 2; c >= i; c--) retVal[n - i - 1, c] = index++;
   //DU
   for (int r = n - i - 2; r > i; r--) retVal[r, i] = index++;
  }

  return retVal;
 }
}

Comments

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons