[Copy question]:
Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X in Spiral Order.
Example 1:
input:[[1, 2, 3], [4, 5, 6], [7, 8, 9]]output: [1,2,3,6,9,8,7,4,5]
Example 2:
input:[ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12]]output: [1,2,3,4,8,12,11,10,9,5,6,7]
[Brute force solution]:
Time Analysis:
Spatial Analysis:
[After optimization]:
Time Analysis:
Spatial Analysis:
[Wonderful output CONDITIONS]:
[Wonderful corner case]:
After the variable is changed, the if control range is used, otherwise it will be out of bounds:
if <= rowend && colbegin <= colend)
[Thinking questions]:
The feeling indicates that the variable of corner is always changed, bad expression. New four new variables on the line, anyway do not occupy space.
[English data structure or algorithm, why not other data structures or algorithms]:
[a sentence of thought]:
[input]: null: Normal: Large: Extra Small: Special cases handled in the program: abnormal conditions (unreasonable input):
[Drawing]:
[One brush]:
- Start/end are to be added ( including in) the number, so be sure to write the equal sign
[Two brushes]:
[Three brushes]:
[Four brushes]:
[Five brushes]:
[Results of five-minute visual debug]:
[Summary]:
Newly opened several recorded variables that do not occupy space
[Complexity]:time Complexity:o (n) Space complexity:o (n)
[Algorithmic thinking: Iterative/recursive/split/greedy]:
[Key templating code]:
[Other solutions]:
[Follow up]:
[The problem given by the LC becomes variable]:
[Code Style]:
[Whether to write this type of driver Funcion code for the first time]:
[Subtext]:
Public classSolution { PublicList<integer> Spiralorder (int[] matrix) {List<Integer> res =NewArraylist<integer>(); if(Matrix.length = = 0) { returnRes; } intRowbegin = 0; intRowend = matrix.length-1; intColbegin = 0; intColend = matrix[0].length-1; while(Rowbegin <= rowend && colbegin <=colend) { //Traverse Right for(intj = Colbegin; J <= Colend; J + +) {Res.add (matrix[rowbegin][j]); } rowbegin++; //Traverse Down for(intj = Rowbegin; J <= Rowend; J + +) {Res.add (matrix[j][colend]); } colend--; if(Rowbegin <= rowend && colbegin <=colend) { //Traverse Left for(intj = colend; J >= Colbegin; J--) {Res.add (matrix[rowend][j]); }} rowend--; if(Colbegin <= colend && rowbegin <=rowend) { //Traver up for(intj = rowend; J >= Rowbegin; J--) {Res.add (Matrix[j][colbegin]); }} Colbegin++; } returnRes; }}
View Code
Spiral matrix output arrays in spiral order