问题描述
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
输入格式
输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
输出格式
输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。
样例输入
3 3
1 2 3
4 5 6
7 8 9
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 2
3 4
5 6
样例输出
1 3 5 6 4 2
运行超时-------
package com.xjj.lanqiao;
import java.util.Scanner;
public class Lq2_25 {
public static int m;
public static int n;
public int[][] book = new int[m][n];
public void print(int[][] a, int st, int sy){
int[][] next = {{1,0}, //向下走
{0,1}, //向右走
{-1,0}, //向上走
{0,-1}}; //向左走
int x = st, y = sy,k;
int sum = m * n;
book[x][y] = 1;
System.out.print(a[x][y] + " ");
while(sum != 1){
for(k = 0; k <= 3; k++){
x = x + next[k][0];
y = y + next[k][1];
if (sum == 1) {
break;
}
while(x >= 0 && x < m && y >= 0 && y < n && book[x][y] == 0){
System.out.print(a[x][y] + " ");
book[x][y] = 1;
sum--;
x = x + next[k][0];
y = y + next[k][1];
}
x = x - next[k][0];
y = y - next[k][1];
}
}
}
public static void main(String[] args) {
System.out.println();
Scanner scanner = new Scanner(System.in);
m = scanner.nextInt();
n = scanner.nextInt();
int[][] a = new int[m][n];
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++){
a[i][j] = scanner.nextInt();
}
Lq2_25 lq = new Lq2_25();
lq.print(a, 0, 0);
}
}