java将矩阵旋转45度输出

例如:

A B C D E 
F G H I J 
K L M N O 
P Q R S T 
U V W X Y 
    E    
   D J   
  C I O  
 B H N T 
A G M S Y
 F L R X 
  K Q W  
   P V   
    U    

这里写图片描述

思路如上图:
在菱形之外的都是空格,菱形之内(可以使用函数判断)有两种点,一种是有字符,一种是空格
可以发现,有字符的位置(col-row)%2 == 0;接下来寻找45度菱形和矩形的对应关系,row’=(col-row)/2 ,col’=col-row’

完整代码如下:

public class PrintMatrixTrans45degree 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello World!");
        int c=0;
        char[][] arr = new char[5][5];
        for(int i = 0 ; i < 5; i++){
            for(int j = 0; j < 5; j ++){
                arr[i][j]= (char)('A' + c);
                c++;
            }
        }
        for(int i = 0 ; i < 5; i++){
            for(int j = 0; j < 5; j ++){
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
        for(int i = 4; i >= -4; i--){
            int row = 0;
            int col = 0;
            for(int j = 0; j <= 8 ; j ++){
                if(isArea(i,j)){
                    if((j-i)%2 == 0){
                        //打印字母
                        row = (j - i)/2;
                        col = j - row;
                        System.out.print(arr[row][col]);
                    }else{
                        System.out.print(" ");
                    }                   
                }else{
                    //打印空格
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

    public static boolean isArea(int row , int col){
        if(row <= col &&  row >= col - 8 && row >= -col && row <= -col + 8  ){
            //System.out.println("("+row+","+col+")");
            return true;
        }
        return false;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值