当前位置:   article > 正文

[LeetCode Solution 54] Spiral Matrix

[LeetCode Solution 54] Spiral Matrix
Question:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].



Answers:
*************************************************************
Approach #1 Using Assitant Matrix

Intuition

This method is straight forward,
we are using an assistant matrix to help us
to record the visiting information,
i.e. when we meet the board or the element in the matrix has been visited,
we have to change the direction.

Algorithm

  1. Here are some comments before going into the strategy:
  2. 1. we can visit all the elements in matrix[m,n] in m*n steps, so the loop is m*n and time complexity is $O(m*n)$
  3. 2. there are 4 directions, right ->down -> left -> up and the back to the right, the order of the direction will not change.
  4. which means after going right and we have to change direction to down for sure.
  5. 3. how can we check if we have to change the direction or not?
  6. a) when we reach the border of the matrix;
  7. b) when we reach the elements we have been visited;
  8. The strategy is as follows:
  9. Step1: denote num_row as matrix.row_length, num_col as matrix.column_length
  10. and initial checker[][] which help us to check if the elements in the matrix has been visited or not
  11. Step2: while not finish visiting all the elements in matrix
  12. -> check if can continue to go right
  13. if yes
  14. continue to go right and add the element in the result list
  15. set the position in checker as true;
  16. -> check if can continue to go down
  17. if yes
  18. continue to go down and add the element in the result list
  19. set the position in checker as true;
  20. -> check if can continue to go left
  21. if yes
  22. continue to go left and add the element in the result list
  23. set the position in checker as true;
  24. -> check if can continue to go up
  25. if yes
  26. continue to go up and add the element in the result list
  27. set the position in checker as true;
  28. Step3: return result list.

Java

  1. public class Solution {
  2. public List<Integer> spiralOrder(int[][] matrix) {
  3. List<Integer> res = new ArrayList<>();
  4. if (matrix.length == 0)
  5. return res;
  6. int num_row = matrix.length;
  7. int num_col = matrix[0].length;
  8. boolean[][] checker = new boolean[num_row][num_col];
  9. // Initial
  10. int row = 0, col = 0, flag = 0;
  11. res.add(matrix[row][col]);
  12. checker[row][col] = true;
  13. while (flag<num_row*num_col-1) {
  14. // move right
  15. while ((col + 1 < num_col) && (checker[row][col + 1] == false)) {
  16. col++;
  17. flag++;
  18. res.add(matrix[row][col]);
  19. checker[row][col] = true;
  20. }
  21. // move down
  22. while ((row + 1 < num_row) && (checker[row + 1][col] == false)) {
  23. row++;
  24. flag++;
  25. res.add(matrix[row][col]);
  26. checker[row][col] = true;
  27. }
  28. // move left
  29. while ((col > 0) && (checker[row][col - 1] == false)) {
  30. col--;
  31. flag++;
  32. res.add(matrix[row][col]);
  33. checker[row][col] = true;
  34. }
  35. // move up
  36. while ((row > 0) && (checker[row - 1][col] == false)) {
  37. row--;
  38. flag++;
  39. res.add(matrix[row][col]);
  40. checker[row][col] = true;
  41. }
  42. }
  43. return res;
  44. }
  45. }

Complexity Analysis

  • Time complexity : O(mn). where m and n are rows and columns,
    we just need to check all the elements in the matrix, and no repeat visiting.

  • Space complexity: $$O(mn)$$, we use checker matrix to store the visited elements information. and mn length result list.


Approach #2 Without Assisting Matrix [Accepted]

Can we do better? Can we design an algorithm not using helper matrix? Yes,
The strategy is: update matrix border.
1.png
As shown in the picture, every time we change the direction, we have to update border. For example,
first, we go right as possible as we can and set blue as the new top border.
So we can not visit the first row anymore, the highest row we can visit becomes the second row (row+1)...
Therefore, we can implement the traverse strategy by updating the border.

Algorithm

  1. while(topBoarder<=bottomBoarder && leftBoarder <= rightBoarder)
  2. 1. go right as much as possible (when visiting the right border, go to 2)
  3. increase top border;
  4. 2. go down as much as possible (when visiting the bottom border, go to 3)
  5. decrease right border;
  6. 3. go left as much as possible (when visiting the left border, go to 4)
  7. decrease bottom border;
  8. 4. go up as much as possible (when visiting the top border, back loop)
  9. increase left boarder;

Java

  1. public class Solution {
  2. public List<Integer> spiralOrder(int[][] matrix) {
  3. List<Integer> res = new ArrayList<>();
  4. if (matrix.length == 0) {
  5. return res;
  6. }
  7. int topBorder = 0, bottomBorder = matrix.length - 1;
  8. int leftBorder = 0, rightBorder = matrix[0].length - 1;
  9. while (topBorder <= bottomBorder && leftBorder <= rightBorder) {
  10. // Traverse Right
  11. for (int j = leftBorder; j <= rightBorder; j++) {
  12. res.add(matrix[topBorder][j]);
  13. }
  14. topBorder++;
  15. // Traverse Down
  16. for (int j = topBorder; j <= bottomBorder; j++) {
  17. res.add(matrix[j][rightBorder]);
  18. }
  19. rightBorder--;
  20. if (topBorder <= bottomBorder) {
  21. // Traverse Left
  22. for (int j = rightBorder; j >= leftBorder; j--) {
  23. res.add(matrix[bottomBorder][j]);
  24. }
  25. }
  26. bottomBorder--;
  27. if (leftBorder <= rightBorder) {
  28. // Traverse Up
  29. for (int j = bottomBorder; j >= topBorder; j--) {
  30. res.add(matrix[j][leftBorder]);
  31. }
  32. }
  33. leftBorder++;
  34. }
  35. return res;
  36. }
  37. }

A Comment
Please pay attention that before go in traverse left loop and traverse up loop,
there is an if statement. Why we need this?

Because that the top Boarder and right border have been updated.
if top Border > bottom Boarder which means the row == top Border == bottom Boarder has been visited, we do not need to visit once more.
In a word, this is to avoid duplications.

for example: the matrix just have one row {{1,2,3}};

after the traverse right loop, top border = 1;

after the traverse down loop, right border = 1;

not go into traverse left loop where top boarder = 1 > bottom boarder = 0;

not go into traverse up loop where top boarder = 1 > bottom boarder = 0;

Complexity Analysis

  • Time complexity: O(m*n)

  • Space complexity: O(m*n). we use result list which length is m*n

Video Explanation
[Video Explanation 54]

LeetCode Tutorial

[LeetCode Solution 54]


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/思考机器3/article/detail/62918?site
推荐阅读
相关标签
  

闽ICP备14008679号