Tuesday, September 1, 2015

[Matrix] Spiral Matrix II

1. Example
Spiral Matrix II "Fill in"
Filled a square matrix with elements from 1 to n^2 in spiral order
Given  n =3,
you should return the following matrix:
[
[1,2,3],
[8,9,4],
[7,6,5]
]

2. Implementation
Q1: using the technique used in Spiral order ?
A1: just using a count as a value to fill in the matrix,
top->             matrix[levelNum][j],   j >= levelNum  , j  < matrix[0].length -levelNum -1
right->           matrix[i][matrix[0].length-1-levelNum],  i>= levelNum, i < matrix.length-1-levelNum
bottom->       matrix[matri.length-1-levelNum][j], j < = matrix[0].length-1-levelNum ,  j > levelNum
left     - >       matrix[i][levelNum],   i <= matrix.length -1 -levelNum , i  > levelNum
Q1: what about rotate image ?
A1:

for (int levelNum= 0 , levelNum < size/2; levelNum++)
for (int j = levelNum; j< matrix.length-1-levelNum; j++)
int temp = matrix[levelNum][j];
matrix[levelNum][j] = matrix[matrix.length-1-j][levelNum];//topleft<-bottomleft
matrix[matrix.length-1-j][levelNum]= matrix[matrix.length-1-levelNum][matrix.length-1-j]// bottomleft<-bottomright
matrix[matrix.length-1-levelNum][matric.length-1-j] = matrix[j][matrix.length-1-levelNum]// botomright<-topright
matrix[j][matrix.length-1-levelNum] =temp;

// Time:O(nxn), Space:O(1)
public int[][] generateMatrix(int n)
{


        
      int[][] res = new int[n][n];




      // validate the input
      if ( n < 0)
           return matrix;




      int k =1;
      for (int levelNum = 0; levelNum < n/2; levelNum++)
      { 
             // top
             for (int j = levelNum ; j < n - 1 -levelNum; j++)
                   res[levelNum][j] = k++;
             // right
             for (int i = levelNum; i < n-1-levelNum; i++)
                   res[i][n-1-levelNum] = k++;
             // bottom
             for (int j = n-1-levelNum; j > levelNum;j--)
                   res[n-1-levelNum][j]= k++;
             // left
             for (int i= n-1 -levelNum; i > levelNum; i--)
                   res[i][levelNum] = k++;
      } 


      
      // Fro Square Matrix, odd length only got one element left inner most layer
      if (n%2 ==1)
          res[n/2][n/2] = k;




      return res;




}

int [][] res = new int[n][n];
int k=1;
int top = 0, bottom = n-1, left = 0, right = n-1;








while (left < right && top < bottom)
{




     for (int j = left; j < right;j++)
           res[top][j] = k++;
     for (int i =top; i < bottom; i++)
           res[i][right] = k++;
     for (int j = right ; j > left; j--)
           res[bottom][j] = k++;
     for (int i = bottom; i > top)
          res[i][left] = k++;



left++;
right--;
top++;
bottom--;

}




      if (n%2 ==1)
          res[n/2][n/2] = k;




return res;
3. Similar ones
(M) Spiral Matrix
Rotate Image

No comments:

Post a Comment