Data Structures in Java/Must Know Questions

rotateImage

cat_no2 2021. 11. 30. 17:21

perfect square comes to row and column 

rotate the image by 90 degrees clockwise 

1 2 3           7 4 1

4 5 6   ->   8 5 2

7 8 9          9 6 3

 

0,0 0,1 0,2 -> 0,2, 1,2 2,2 

 

1,0 1,1 1,2  -> 0,1 1,1 2,1 

 

2,0 2,1 2,2 -> 0,0 1,0 2,0 

 

transpose 

just swap row and column -> then change the order of column 

123        147 

456 ->  258 -> 

789       369 

swap a[i,j] = a[j, i]; 

 

 

int [] [] rotateImage(int [] [] matrix){
	int N = maxtrix.length; 
    
    //swap col and row 
    for(int i=0; i<N; i++){
    	for(int j=i; j<N; j++){
        	int temp = matrix[i][j];
       		matrix[i][j] = matrix[j][i];
        	matrix[j][i] = temp;
        }
    }
    
    //Rearrange the order of column - flip horizontally 
    for(int i=0; i<N; i++){
      for(int j=0; j<N/2; i++){
          int temp = matrix[i][j];
          matrix[i][j] = matrix[i][N-1-j];
          matrix[i][N-1-j] = temp; 
      }
    }
}

 

 

'Data Structures in Java > Must Know Questions' 카테고리의 다른 글

longestPalindrome  (0) 2021.12.01
firstDuplicate  (0) 2021.12.01
maximum sum subrray  (0) 2021.12.01
firstNonRepeatingCharacter  (0) 2021.12.01
sumOfTwo  (0) 2021.11.30