(Java)蛇形方阵与杨辉三角

11 篇文章 0 订阅

蛇形方阵与杨辉三角

PS:原题来自洛达

蛇形方阵

Java代码
输入整数n, 输出n*n的蛇形方阵

import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static int fabs(int a, int b) {
        int c = a - b;
        if (c < 0)
            c = 0 - c;
        return c;
    }
    
    
    public static void main(String args[]) throws Exception {
        Scanner cin=new Scanner(System.in);
        int ans = 0;
        int min = Integer.MAX_VALUE;
        int max = -1;
        int len = 10;
        int n = cin.nextInt();
        int cnt = 1;
        int[][] arr = new int[len][len];
        int x=1,y=0;
        while(cnt <= n*n) {
            while(y < n && arr[x][y+1] == 0) {
                arr[x][++y] = cnt++;
            }
            while(x < n && arr[x+1][y] == 0) {
                arr[++x][y] = cnt++;
            }
            while(y > 1 && arr[x][y-1] == 0) {
                arr[x][--y] = cnt++;
            }
            while(x > 1 && arr[x-1][y] == 0) {
                arr[--x][y] = cnt++;
            }
        }
        
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                System.out.printf("%3d",arr[i][j]);
            }
            System.out.println();
        }
        
        
        
    }
}
样例

yE6OG6.md.png

杨辉三角

杨辉三角百度百科

Java代码

import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static int fabs(int a, int b) {
        int c = a - b;
        if (c < 0)
            c = 0 - c;
        return c;
    }
    
    
    public static void main(String args[]) throws Exception {
        Scanner cin=new Scanner(System.in);
        int ans = 0;
        int min = Integer.MAX_VALUE;
        int max = -1;
        int len = 30;
        int n = cin.nextInt();
        int cnt = 1;
        int[][] arr = new int[len][len];
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                if(i >= j) {
                    if(j == 1)
                        arr[i][j] = 1;
                    else
                        arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
                }
            }
        }
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                if(i >= j)
                    System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
        
        
    }
}
样例

杨辉三角yzdong

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值