计蒜客—矩阵翻转(简单)
最后更新于:2022-04-01 09:41:05
做这道题的过程中,了解到java的二维数组实际上就是多个一维数组的数组,所以类似下面这样的赋值是可以实现的.
~~~
public static void upturn(int d[][],int a,int b) {
int[] e = new int[b];
for (int i = 0; i < a/2; i++) {
e = d[i];
d[i] = d[a-i-1];
d[a-i-1] = e;
}
}
~~~
有了这个特性,那么矩阵翻转就变得很方便了,不过左右翻转,这个倒是没法实现
完整代码如下:
~~~
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int a,b,c;
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
int[][] d = new int[a][b];
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
d[i][j] = input.nextInt();
}
}
if(c == 1){
upturn(d, a, b);
}else {
leftturn(d, a, b);
}
for (int[] is : d) {
for (int i : is) {
System.out.print(i+" ");
}
System.out.println();
}
}
public static void upturn(int d[][],int a,int b) {
int[] e = new int[b];
for (int i = 0; i < a/2; i++) {
e = d[i];
d[i] = d[a-i-1];
d[a-i-1] = e;
}
}
public static void leftturn(int d[][],int a,int b) {
int temp;
for (int i = 0; i < b/2; i++) {
for (int j =0 ; j < a; j++) {
temp = d[j][i];
d[j][i] = d[j][b-i-1];
d[j][b-i-1] = temp;
}
}
}
}
~~~