首页 > 代码库 > Spiral Matrix

Spiral Matrix

Problem

Given aNXN matrix, starting from the upper right corner of the matrix start printingvalues in a counter-clockwise fashion.
E.g.: Consider N = 4
Matrix= {a, b, c, d,
e, f, g, h,
i, j, k, l,
m, n, o, p}
Your function should output: dcbaeimnoplhgfjk

Solution

 1 public ArrayList<Integer> spiralOrder(int[][] matrix) { 2     ArrayList<Integer> res = new ArrayList<Integer>(); 3      4     if(matrix == null || matrix.length == 0) { 5         return res; 6     } 7      8     int row = matrix.length; 9     int col = matrix[0].length;10     11     int x = 0;12     int y = 0;13     while(row > 0 && col > 0) {14         //if row or col == 1, no circle can be found15         if(row == 1) {16             for(int i=0; i<col; i++) {17                 res.add(matrix[x][y++]);18             }19             break;20         }21         if(col == 1) {22             for(int i=0; i<row; i++) {23                 res.add(matrix[x++][y]);24             }25             break;26         }27         28         //row left to right29         for(int i=0; i<col-1; i++) {30             res.add(matrix[x][y++]);31         }32         //col high to low33         for(int i=0; i<row-1; i++) {34             res.add(matrix[x++][y]);35         }36         //row right to left37         for(int i=0; i<col-1; i++) {38             res.add(matrix[x][y--]);39         }40         //col low to high41         for(int i=0; i<row-1; i++) {42             res.add(matrix[x--][y]);43         }44         45         row = row - 2;46         col = col - 2;47         x++;48         y++;49         50     }51     52     return res;53 }

 

Spiral Matrix