2D matrix questions
unknown
java
5 months ago
1.8 kB
189
Indexable
// only valid for square matrix public int[][] transpose(int[][] matrix) { int n = matrix.length; int curr_r = 0; int curr_c = 0; while(curr_r<n){ int i = curr_r; for(int j = curr_c; j<n; j++){ // swap row, col wit int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } curr_r++; curr_c++; } return matrix; } public static void printSpiral(int[][] matrix){ int n = matrix.length; int m = matrix[0].length; int sr = 0, sc = 0, er = n-1, ec = m-1; int row,col; while(sr<=er && sc<=ec){ // print starting col from sr to er col = sc; for(row=sr; row<=er && sc<=ec; row++){ System.out.print(matrix[row][col] + ", "); } sc++; // print ending row from sc to ec row = er; for(col = sc; col<=ec && sr<=er; col++){ System.out.print(matrix[row][col] + ", "); } er--; // print ending col from er to sr col = ec; for(row=er; row>=sr && sr<=er && sc<=ec; row--){ System.out.print(matrix[row][col] + ", "); } ec--; // print starting row from ec to sc row = sr; for(col = ec; col>=sc && sr<=er && sc<=ec; col--){ System.out.print(matrix[row][col] + ", "); } sr++; System.out.println(); } } public static void main(String[] args){ int[][] arr = {{1,6,11,14,21}, {2,7,12,15,25}, {3,8,13,16,22}, {4,9,17,19,24}, {5,10,20,18,23}}; printSpiral(arr); }
Editor is loading...
Leave a Comment