1.题目描述
—个公司做团建活动,排成1个M行N列的队形。左上角的同事编号为(0,0),右下角的同事编号为(M-1,N-1)。
为了打散队伍重新分组。
从队列左上角同事开始从1开始报数,最外圈的同事按顺时针报数。
外圈同事全部报完,内圈的同事按同样规则继续报数.
个位数为7且十位数为奇数被挑选出来作为特战队员。
请设计一个计算的方法,入参是两个大于等于10且小于等于1000的整数,M和N。
请按报数顺序输出特战队员的编号列表(N*2的二维数组)
非法输入请返回内容为空的数组
2.输入输出描述
输入描述:
入参是两个整数M和N,值范围为:[10,1000]。单空格分隔,格式如:
10 10
输出描述:
请按报数顺序输出特战队员的编号列表(N * 2的二维数组)
非法输入请返回内容为空的数组。
俞出样例:
[[7, 9], [1, 1], [8, 2], [7, 5], [4, 4]]
代码实现
public class ReverseOnly {
public static void main(String[] args){
int i = 0;
Scanner n = new Scanner(System.in);
System.out.println("请输入参数M和N, 空格隔开");
int M = n.nextInt();
int N = n.nextInt();
System.out.println("输出");
num(M, N);
i++;
}
public static Map<Integer, int[]> toMap = new HashMap<>();
public static int[][] num(int M, int N) {
int[][] res = new int[M * N][];
int[][] arr = creat(M, N);
int[] ans = spiralOrder(arr);
int resi = 0;
for (int i = 1; i < M * N; i++){
int numA = i % 10, numB = (i % 100) / 10;
if ((numA == 7) && (numB % 2 == 1)) {
int[] t = toMap.get(i);
res[resi++] = t;
}
}
// resi;
int[][] result = new int[resi][1];
for (int j = 0; j < resi; j++) {
result[j] = res[j];
}
System.out.println(Arrays.deepToString(result));
return result;
}
// 正常构造二维数组
public static int[][] creat(int N, int M) {
int[][] res = new int[M][N];
int index = 1;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++){
res[i][j] = index++;
int[] temp = new int[]{i, j};
toMap.put(index, temp);
}
}
return res;
}
// 逆时针输出数组
public static int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int rows = matrix.length, columns = matrix[0].length;
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
int[] order = new int[total];
int row = 0, column = 0;
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int directionIndex = 0;
int index = 1;
for (int i = 0; i < total; i++) {
order[i] = matrix[row][column];
int[] temp = new int[]{row, column};
toMap.put(index++, temp);
visited[row][column] = true;
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
}