# 蓝桥杯练习系统回形取数VIP Basic-25

package Basic_VIP;

import java.util.Scanner;

/**
* 时空复杂度都太大
* @author DemoRosie
* 运行超时，有一个还超出内存
*/
public class Basic_25 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);

int m = in.nextInt();//行
int n = in.nextInt();//列
int num;
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
num = in.nextInt();
arr[i][j] = num;
}
}
/**
* 从（0，0）开始，（0，0）——>（1，0）为初始方向，取过的位置置0，num为正整数
*/
int row = 0;
int col = 0;
int index = 0;
/**
* direction ：1，2，3，4分别指示四个方向
*/
int direction = 1;
String temString = "";
while(true) {
if (direction == 1) {
//j不变，i变
for (int i = row; i < m - index ; i++) {
if (arr[i][col] == -1) {
break;
}
temString += arr[i][col]+" ";
arr[i][col] = -1;
}
direction = 2;
col++;
row = m - index-1;
}
if (direction == 2) {
//i不变，j变
for (int j = col; j < n-index; j++) {
if (arr[row][j] == -1) {
break;
}
temString += arr[row][j]+" ";
arr[row][j] = -1;
}
direction = 3;
row --;
col = n-index-1;
}
if (direction == 3) {
//j不变，i变
for (int i = row; i >= index ; i--) {
if (arr[i][col] == -1) {
break;
}
temString += arr[i][col]+" ";
arr[i][col] = -1;
}
direction = 4;
col--;
row = index;

}
if (direction == 4) {
//i不变，j变
//打印完之后，说明这一圈万事了，进入下一圈，下一圈index++，让最初的col和row都等于index
for (int j = col; j > index; j--) {
if (arr[row][j] == -1) {
break;
}
temString += arr[row][j]+" ";
arr[row][j] = -1;
}
index ++;
col = index;
row = index;
direction = 1;
if (index == m || index == n) {
break;
}
}
}
System.out.println(temString);
}
}


• 0
点赞
• 0
评论
• 0
收藏
• 打赏
• 扫一扫，分享海报

02-28 232

01-09 120
05-06 355
03-29 35
05-22 1262
01-29 166
04-09 30
03-11 160

DemoRosie

¥2 ¥4 ¥6 ¥10 ¥20

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