756. 蛇形矩阵
输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5
在题解区看到一个非常妙非常好理解的写法!!!故此记录。
对于矩阵填数的问题,都可以用这种方式解决了。
import java.util.Scanner;
/**
* @program: AcWing
* @description:
* @author: zjx
* @create: 2022-08-01 12:05
**/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int[][] g=new int[105][105];
int left=0,right=m-1,top=0,bottom=n-1;
int cnt=1;
while(left<=right&&top<=bottom){
//向右
for(int i=left;i<=right;i++){
g[top][i]=cnt++;
}
//向下
for(int i=top+1;i<=bottom;i++){
g[i][right]=cnt++;
}
//向左
for(int i=right-1;i>=left && top < bottom;i--){
// 注意条件,否则往回写会覆盖…… 比如输入 1 4,只要执行向右就行,然而不加这个语句 top==bottom就会覆盖之前写的导致错误
g[bottom][i]=cnt++;
}
//向上
for(int i=bottom-1;i>=top+1 && left<right;i--){
// 注意条件
g[i][left]=cnt++;
}
left++;right--;top++;bottom--;
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
System.out.print(g[i][j]+" ");
}
System.out.println();
}
}
}
AcWing753. 平方矩阵 I
输入样例:
1
2
3
4
5
0
输出样例:
1
1 1
1 1
1 1 1
1 2 1
1 1 1
1 1 1 1
1 2 2 1
1 2 2 1
1 1 1 1
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
如果用之前的方法,虽然也比较简单,但是只能用于n×n矩阵(无法套用在n×m矩阵中)
import java.util.Scanner;
/**
* @program: AcWing
* @description:
* @author: zjx
* @create: 2022-08-01 12:05
**/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int n=sc.nextInt();
if(n==0) break;
int[][] g=new int[105][105];
int si=0,sj=0;
int cnt=n-1;
int s=1;
int i,j;
// 向右
while(cnt>0) {
for (j = sj; j < sj + cnt; j++) {
g[si][j] = s;
}
//向下
for (i = si; i < si + cnt; i++) {
g[i][j] = s;
}
//向左
for (j = sj + cnt; j > sj; j--) {
g[i][j] = s;
}
//向上
for (i = si + cnt; i > si; i--) {
g[i][j] = s;
}
s++;
si++;
sj++;
cnt -= 2;
}
if(n%2==1) g[si][sj]=s;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.print(g[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
}
}
借鉴了756 蛇形矩阵问题后:
import java.util.Scanner;
/**
* @program: AcWing
* @description:
* @author: zjx
* @create: 2022-08-01 12:05
**/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int[][] g=new int[105][105];
int left=0,right=n-1,top=0,bottom=n-1;
int cnt=1;
while(left<=right&&top<=bottom){
//向右
for(int i=left;i<=right;i++){
g[top][i]=cnt;
}
//向下
for(int i=top+1;i<=bottom;i++){
g[i][right]=cnt;
}
//向左
for(int i=right-1;i>=left && top < bottom;i--){
// 注意条件,否则往回写会覆盖…… 比如输入 1 4,只要执行向右就行,然而不加这个语句 top==bottom就会覆盖之前写的导致错误
g[bottom][i]=cnt;
}
//向上
for(int i=bottom-1;i>=top+1 && left<right;i--){
// 注意条件
g[i][left]=cnt;
}
left++;right--;top++;bottom--;
cnt++;
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(g[i][j]+" ");
}
System.out.println();
}
}
}