LeetCode Spiral Matrix II Solution Explained - Java

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

Excellent video. Thank you Nick for making these videos.

Below is an alternative solution I developed. It uses a single "level" tracker, rather than the row start + end and column start + end trackers. Each level is one "spiral" around the outside edge of the currently active region.

public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];

int level = 0;

int currentNumber = 1;

while (level <= (n / 2)) {
// fill in top row
for (int i = level; i < n - level; i++) {
matrix[level][i] = currentNumber++;
}

// fill in right side column
for (int i = level + 1; i < n - level; i++) {
int columnIndex = n - level - 1;
matrix[i][columnIndex] = currentNumber++;
}

// fill in bottom row
for (int i = n - level - 2; i >= level; i--) {
int rowIndex = n - level - 1;
matrix[rowIndex][i] = currentNumber++;
}

// fill in left side column
for (int i = n - level - 2; i > level ; i--) { /* the "> level" bound takes care of not overlapping with
the top row that's already been filled in for tis level */
matrix[i][level] = currentNumber++;
}

level++;
}

return matrix;
}

culleyb
Автор

Thanks for the simple and clear explanation!
This solution is easy understanding than LeetCode Editorials.

Demonic
Автор

thanks alot nick already saw the last video just saw this video if I could learn something new and guess what I did thanks.

satyamgupta
Автор

Hi Nick can you make a video for Spiral Matrix III (885)? I am still confused it. Thank you

hhjdkdnchidnd
Автор

buddy can you do spiral 3 in leetcode?

velmuruganr
Автор

Hi,
Great video
Can you make a video for spiral matrix 3 885 leetcode medium ?

deepeshgurnani