关于矩阵变换的小问题

一个网友问了一个这样的问题,问题的内容如下:

在控制台输入一个整数4等到下面的矩阵,

0  1  2  3
1  1  2  3
2  2  2  3
3  3  3  3

 

 

 然后通过矩阵变换成如下状态:

0  0  0  0 
 0  1  1  1 
 0  1  2  2 
0  1  2  3
首先,第一个思路是想到的思路是利用矩阵变化公式,但是,头脑里想不起来半个公式。所以,这个思路放弃。
然后,通过观察这个矩阵的特点是个对称的(对称矩阵),变化后的矩阵也是对称的,通过根数组结合起来思考,我突然发现了一个规律,如下所示:
                            (1)
0123   ----  (i,j)---    (0,0)(0,1)(0,2)(0,3)
1123          映射       (1,0)(1,1)(1,2)(1,3)
2223                       (2,0)(2,1)(2,2)(2,3)
3333                       (3,0)(3,1)(3,2)(3,3)
                            (2)
0000   ----  (i,j)---    (0,0)(0,1)(0,2)(0,3)
0111          映射       (1,0)(1,1)(1,2)(1,3)
0122                       (2,0)(2,1)(2,2)(2,3)
0123                       (3,0)(3,1)(3,2)(3,3)
|------发现规律如下------|
从变化后的矩阵和一个二维数组存储访问下标对比,发现了矩阵(1)是正好是每个存储单元中的最大的下标,矩阵(2)是正好是每个存储单元中的最大的下标这时,解决方案豁然开朗。即,只要写个求最大值和最小值的方法
	public static int max(int x, int y) {
		return x > y ? x : y;
	}
 
	public static int min(int x, int y) {
		return x < y ? x : y;
	}
  我利用Java的简单实现代码如下:
package com.demo;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * about a simple solution to change the matrix
 * 
 * @author Frank
 * @since 1.0
 */
public class Matrix {
	/**
	 * 
	 * @param x
	 *            integer value
	 * @param y
	 *            integer value
	 * @return the minimum value between x and y.
	 */
	public static int min(int x, int y) {
		return x < y ? x : y;
	}
	/**
	 * 
	 * @param x
	 *            integer value
	 * @param y
	 *            integer value
	 * @return the maximum value between x and y.
	 */
	public static int max(int x, int y) {
		return x > y ? x : y;
	}
	public static void main(String[] args) {
		Scanner read = new Scanner(System.in);
	
		int n = 4;//default value
		try {
			n = read.nextInt();
		} catch (InputMismatchException e) {
			
			e.printStackTrace();

		} finally {
			System.out.println("*********变换前的矩阵***********");
			int[][] oldMatrix = new int[n][n];
			for(int i = 0;i<n;i++){
				for(int j = 0;j<n;j++){
					oldMatrix[i][j] = max(i,j);
				}
			}
			
			for(int i = 0;i<n;i++){
				for(int j = 0;j<n;j++){
					System.out.print(oldMatrix[i][j]);
				}
				System.out.println();
				
			}
			
			System.out.println("*********变换后的矩阵***********");
			int[][] newMatrix = new int[n][n];
			for(int i = 0;i<n;i++){
				for(int j = 0;j<n;j++){
					newMatrix[i][j] = min(i,j);
				}
			}
			
			for(int i = 0;i<n;i++){
				for(int j = 0;j<n;j++){
					System.out.print(newMatrix[i][j]);
				}
				System.out.println();
				
			}
			
		}

	}

}
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值