54. Spiral Matrix && 59. Spiral Matrix II

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].

Hide Tags
 Array
Hide Similar Problems
 (M) Spiral Matrix II
 
public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> results = new ArrayList<Integer>();
    int row = matrix.length;
    if (row == 0)
      return results;
    int col = matrix[0].length;

    int rMin = 0;
    int rMax = row - 1;
    int cMin = 0;
    int cMax = col - 1;
    while (rMax >= rMin && cMax >= cMin) {
      for (int c = cMin; c <= cMax; ++c)
        results.add(matrix[rMin][c]);
      ++rMin;
      if(rMin>rMax)
        return results;
        
      for (int r = rMin; r <= rMax; ++r)
        results.add(matrix[r][cMax]);
      --cMax;
      if(cMin>cMax)
        return results;
        
      for (int c = cMax; c >= cMin; --c)
        results.add(matrix[rMax][c]);
      --rMax;
      if(rMin>rMax)
        return results;
        
      for (int r = rMax; r >= rMin; --r)
        results.add(matrix[r][cMin]);
      ++cMin;
      if(cMin>cMax)
        return results;
    }

    return results;
  }
}

 

 

59. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] results = new int[n][];
        for(int i =0; i<n; ++i)
        {
            results[i] = new int[n];    
        }
        
        int rMin = 0;
        int rMax = n - 1;
        int cMin = 0;
        int cMax = n - 1;
        int i = 0;
        while (rMax >= rMin && cMax >= cMin) {
          for (int c = cMin; c <= cMax; ++c)
            results[rMin][c] = ++i;
          ++rMin;
          if(rMin>rMax)
            return results;
            
          for (int r = rMin; r <= rMax; ++r)
            results[r][cMax] = ++i;
          --cMax;
          if(cMin>cMax)
            return results;
            
          for (int c = cMax; c >= cMin; --c)
            results[rMax][c] = ++i;
          --rMax;
          if(rMin>rMax)
            return results;
            
          for (int r = rMax; r >= rMin; --r)
            results[r][cMin] = ++i;
          ++cMin;
          if(cMin>cMax)
            return results;
        }
        
        return results;   
    }
}

 

 

 
posted @ 2016-06-28 12:48  新一代的天皇巨星  阅读(206)  评论(0)    收藏  举报