[LeetCode-interview algorithm classic-Java implementation] [054-Spiral Matrix (Spiral Matrix)], leetcode -- java
[054-Spiral Matrix (Spiral Matrix )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original 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 shoshould return[1,2,3,6,9,8,7,4,5].
Theme
Given a matrix of m * n, enter the spiral order of all elements.
Solutions
The calculation output method is used to process the previous row, the right column, the next row, and the left column until all the elements are processed.
Code Implementation
Algorithm Implementation class
Import java. util. arrayList; import java. util. list; public class Solution {public List <Integer> spiralOrder (int [] [] matrix) {List <Integer> result = new ArrayList <> (50 ); if (matrix = null | matrix. length = 0 | matrix [0]. length = 0) {return result;} // if (matrix. length = 1) {for (int I: matrix [0]) {result. add (I) ;}return result ;}// if (matrix [0]. length = 1) {for (int I = 0; I <matrix. length; I ++) {result. add (matrix [I] [0]);} return result;} // calculates the number of circles int row = matrix. length; int col = matrix [0]. length; int cycle = row <col? Row: col; cycle = (cycle + 1)/2; int round = 0; // record the current cycle int left = 0; int right = matrix [0]. length-1; int top = 0; int down = matrix. length-1; int total = col * row; int count = 0; while (round <cycle) {// The previous row for (int I = left; I <= right & count <total; I ++) {count ++; result. add (matrix [round] [I]);} top ++; // the right column of for (int I = top; I <= down & count <total; I ++) {count ++; result. add (matrix [I] [col-round-1]);} right --; // The next row for (int I = right; I >=left & count <total; I --) {count ++; result. add (matrix [row-round-1] [I]);} down --; // the left column for (int I = down; i> = top & count <total; I --) {count ++; result. add (matrix [I] [round]);} left ++; round ++;} return result ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note Please refer to the source for reprinting at http://blog.csdn.net/derrantcm/article/details/47120491]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.