Turn 2d matrix right

I want the 2d matrix to rotate to the right, it compiles fine, but when I try to run it means that the array index is out of range. For example, I want {{10,20,30}, {40,50,60}} to rotate in {{40,10}, {50,20}, {60,30}}

import java.util.*; public class Rotate{ public static int[][] rotate(int[][] m) { int [][] rotateM = new int[m[0].length][m.length]; for (int i= 0; i< m.length; i++){ for (int j= 0; j< m[0].length; j++){ rotateM[i][j] = m[j][m.length-i-1]; } } return rotateM; } public static void main(String[]args){ int[][]m = {{10,20,30}, {40,50,60}}; System.out.println(Arrays.toString(rotate(m))); } 

}

+4
source share
4 answers

Here is a working example:

 private int[][] rotateMatrix(int[][] matrix) { int backupH = h; int backupW = w; w = backupH; h = backupW; int[][] ret = new int[h][w]; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { ret[i][j] = matrix[w - j - 1][i]; } } return ret; } 

I used this code to rotate my bricks in tetris. This code rotates the matrix clockwise.

+2
source

Looks like you just changed your indexes.

Instead:

 rotateM[i][j] = m[j][m.length-i-1]; 

You should have written:

 rotateM[j][i] = m[m.length-i-1][j]; 
+1
source

Do not increase with i = i++ . Just write i++ .

0
source

First of all, delete i = i ++.

enough i ++ and j ++, initialize your arrays and you have the wrong logic,

 for (int j = 0; j < m[0].Length; j++) for (int i = 0; i < m.Length; i++) rotateM[j][i] = m[m.Length - i - 1][j]; 

Here is what you need.

0
source

Source: https://habr.com/ru/post/1307922/


All Articles