每日一题(小白)暴力娱乐篇30

发布于:2025-04-18 ⋅ 阅读:(16) ⋅ 点赞:(0)

顺时针旋转,从上图中不难看出行列进行了变换。因为这是一道暴力可以解决的问题,我们直接尝试使用行列转换看能不能得到想要的结果。

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
	    int n=scan.nextInt();
	    int m=scan.nextInt();
	    int count=0;
	    for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				arr[i][j]=scan.nextInt();
			}
		}
	    for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				System.out.print(arr[j][i]+" ");
			}
			System.out.println();
		}
		scan.close();
	}

如上图所示我们将行列直接转换,但是我们会得到如下的示例结果。由于在进行行列转换的时候,将预先的3行变成4列,4列变成三行超出了原来的数组长度导致了出现0并且转换错误的情况。接下来我们观察一下顺时针转换的下标的位置变化规律可以发现1 3 5 7由原来的第一行(0,0)~(0,3)转换为第三列(0,2)~(3,2),我们不难发现坐标在原来的基础上实现的是行递增,列不变。

3 4
1 3 5 7
9 8 7 6
3 5 9 7
1 9 3 0 
3 8 5 0 
5 7 9 0 

代码实现👇

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
	    int n=scan.nextInt();
	    int m=scan.nextInt();
	    int count=0;
	    for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				arr[i][j]=scan.nextInt();
			}
		}
	    for (int i = 0; i < m; i++) {//行变为列的大小
			for (int j = n-1; j >=  0; j--) {//列每次按原来的行递减输出
				System.out.print(arr[j][i]+" ");
			}
			System.out.println();
		}
		scan.close();
	}

大家多动手,比较简单


网站公告

今日签到

点亮在社区的每一天
去签到