蛇形方阵与杨辉三角
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();
}
}
}
样例
杨辉三角
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();
}
}
}