身无彩凤双飞翼,心有灵犀一点通。
点赞再看,养成习惯。
问题描述
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
输入格式
输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
输出格式
输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。
样例输入
3 3
1 2 3
4 5 6
7 8 9
样例输出
1 4 7 8 9 6 3 2 5
样例输入
3 2
1 2
3 4
5 6
样例输出
1 3 5 6 4 2
递归
import java.util.Scanner;
public class RecoveryNumber {
//rowIndex 开始行索引
//columnIndex 开始列索引
//rowCount 行的数字个数
//columnCount 列的数字个数
public void output(int[][] nums) {
output(nums, 0, 0, nums.length, nums[0].length);
}
public void output(int[][] arr,int rowIndex,int columnIndex,int rowCount,int columnCount) {
if( rowCount < 1 || columnCount < 1 ) {
return;
}
//取左边的数,共 rowCount 个
for (int i = 0; i < rowCount; i++)
System.out.print(arr[ rowIndex + i][ columnIndex ] + " ");
//取下边的数,共 columnCount-1 个
for (int i = 0; i < columnCount - 1; i++)
System.out.print(arr[ rowIndex + rowCount - 1 ][ columnIndex + 1 + i ] + " ");
//取右边的数,共 rowCount-1 个
for (int i = 0; i < rowCount - 1; i++)
System.out.print(arr[ rowIndex + rowCount -i - 2 ][ columnIndex + columnCount - 1 ] + " ");
//取上边的数,共 columnCount-2 个
for (int i = 0; i < columnCount - 2; i++)
System.out.print(arr[ rowIndex ][ columnIndex + columnCount - 2 - i ] + " ");
//递归下一圈的数字
output(arr, rowIndex + 1, columnIndex + 1, rowCount - 2, columnCount - 2);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RecoveryNumber cs=new RecoveryNumber();
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int[][] arr=new int[m][n];
int nue = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j]=sc.nextInt();
}
}
cs.output(arr);
}
}
Java
import java.io.BufferedInputStream;
import java.util.Scanner;
public class RecoveryNumber2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(new BufferedInputStream(System.in));
int m = scanner.nextInt();
int n = scanner.nextInt();
int[][] s = new int[m][n];
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
s[i][j] = scanner.nextInt();
int ax = 0;
int ay = 0;
int bx = m;
int by = n;
int[] res = new int[200*200];
int j = 0;
while(true) {
for(int i = ax; i < bx; i++)
res[j++] = s[i][ay];
for(int i = ay+1; i < by; i++)
res[j++] = s[bx-1][i];
for(int i = bx-2; i >= ax; i--)
res[j++] = s[i][by-1];
for(int i = by-2; i > ay; i--)
res[j++] = s[ax][i];
ax++; ay++; bx--; by--;
if(ax >= bx || ay >= by)
break;
}
System.out.print(res[0]);
for(int i = 1; i < m*n; i++)
System.out.print(" " + res[i]);
}
}