2015年9月23日星期三

Leetcode 54 Spiral Matrix

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].
Solution 1: coding problem, pay attention to one line situation
 public class Solution {  
   public List<Integer> spiralOrder(int[][] matrix) {  
     List<Integer> res=new ArrayList<>();  
     int m=matrix.length;  
     if (m==0) return res;  
     int n=matrix[0].length;  
     int iLo=0, iHi=m-1;  
     int jLo=0, jHi=n-1;  
     while (iLo<iHi && jLo<jHi) {  
       for (int j=jLo; j<jHi; j++) res.add(matrix[iLo][j]);  
       for (int i=iLo; i<iHi; i++) res.add(matrix[i][jHi]);  
       for (int j=jHi; j>jLo; j--) res.add(matrix[iHi][j]);  
       for (int i=iHi; i>iLo; i--) res.add(matrix[i][jLo]);  
       iLo++; jLo++; iHi--; jHi--;  
     }  
     if (iLo==iHi)  
       for (int j=jLo; j<=jHi; j++) res.add(matrix[iLo][j]);  
     else if (jLo==jHi)  
       for (int i=iLo; i<=iHi; i++) res.add(matrix[i][jLo]);  
     return res;  
   }  
 }  
Solution 2: make code cleaner
 public class Solution {  
   public List<Integer> spiralOrder(int[][] matrix) {  
     List<Integer> res=new ArrayList<>();  
     int m=matrix.length;  
     if (m==0) return res;  
     int n=matrix[0].length;  
     int loRow=0, hiRow=m-1;  
     int loCol=0, hiCol=n-1;  
     while (true) {  
       for (int j=loCol; j<=hiCol; j++) res.add(matrix[loRow][j]);  
       if (++loRow>hiRow) break;  
       for (int i=loRow; i<=hiRow; i++) res.add(matrix[i][hiCol]);  
       if (--hiCol<loCol) break;  
       for (int j=hiCol; j>=loCol; j--) res.add(matrix[hiRow][j]);  
       if (--hiRow<loRow) break;  
       for (int i=hiRow; i>=loRow; i--) res.add(matrix[i][loCol]);  
       if (++loCol>hiCol) break;  
     }  
     return res;  
   }  
 }  

没有评论:

发表评论