题解 | #C翻转#
C翻转
https://www.nowcoder.com/practice/a591300637874f6ba2316a5fe3e94579
import java.util.Arrays; import java.util.Scanner; public class Main { public static void swapMatrix(int[][] temp) { int len = temp.length; int low = 0, high = len - 1; while (low < high) { int[] t1 = Arrays.copyOf(temp[low], len); System.arraycopy(temp[high], 0, temp[low], 0, len); System.arraycopy(t1, 0, temp[high], 0, len); low++; high--; } for (int i = 0; i < len; i++) { for (int j = 0; j <= i; j++) { int k = temp[i][j]; temp[i][j] = temp[j][i]; temp[j][i] = k; } } } public static void matrixReverse(int[][] matrix, int startRow, int endRow, int startCOl, int endCol, boolean flag) { int len = endRow - startRow + 1; int[][] temp = new int[len][len]; if (flag) { for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { temp[i][j] = matrix[i + startRow][j + startCOl]; } } swapMatrix(temp); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { matrix[i + startRow][j + startCOl] = temp[i][j]; } } } else { for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { temp[i][j] = matrix[j + startRow][i + startCOl]; } } swapMatrix(temp); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { matrix[startRow + j][startCOl + i] = temp[i][j]; } } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int[][] matrix = new int[5][5]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { matrix[i][j] = scanner.nextInt(); } } int op1 = scanner.nextInt(); int op2 = scanner.nextInt(); int startRow = scanner.nextInt() - 1; int startCol = scanner.nextInt() - 1; matrixReverse(matrix, startRow, (op2 == 2 ? startRow + 1 : startRow + 2), startCol, (op2 == 2 ? startCol + 1 : startCol + 2), op1 == 1 ); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } } }