Preface The first blog of the New Year should first come to a problem-solving report, mainly because I was too lazy to take care of my New Year's Eve. My girlfriend had a fever and did not have time to write a year-end summary, I have some experience in the Problem Solving report. I will share it with you!
Here, I wish you a happy New Year and good luck.
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:
You shoshould return [1, 2, 3, 6, 9, 8, 7, 4, 5].
The idea is to parse the matrix in the order of (top-> right-> bottom-> left) and consider the situation where only one row or only one column exists. Do not worry.
AC code
public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { int minX, minY, maxX, maxY, x, y; ArrayList<Integer> list = new ArrayList<Integer>(); // special case if (matrix == null || matrix.length == 0) { return list; } // initial variable minX = minY = 0; maxX = matrix.length - 1; maxY = matrix[0].length - 1; for (; minX <= maxX && minY <= maxY; minX++, minY++, maxX--, maxY--) { x = minX; y = minY; list.add(matrix[x][y]); // only a row if (minX == maxX) { for (y += 1; y <= maxY; y++) { list.add(matrix[x][y]); } break; } // only a column if (minY == maxY) { for (x += 1; x <= maxX; x++) { list.add(matrix[x][y]); } break; } // a square for (y += 1; y <= maxY; y++) { // top list.add(matrix[x][y]); if (y == maxY) break; } for (x += 1; x <= maxX; x++) { // right list.add(matrix[x][y]); if (x == maxX) break; } for (y -= 1; y >= minY; y--) { // bottom list.add(matrix[x][y]); if (y == minY) break; } for (x -= 1; x > minX; x--) { // left list.add(matrix[x][y]); if (x == minX + 1) break; } } return list; }}