问题描述
回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转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
方法1
import java.util.Scanner;
public class Main
{
static int k[][];
public static void main(String args[])
{
Scanner cn=new Scanner(System.in);
int q=cn.nextInt();
int w=cn.nextInt();
k=new int[q+1][w+1];
for(int i=1;i<=q;i++)
for(int j=1;j<=w;j++)
k[i][j]=cn.nextInt();
String str="";
int a=1,i=0,x=1,y=1;
while(true)
{
if(i==q*w)break;
str=str+k[x][y]+" ";
i++;x++;
while(x<=q-a)
{
str=str+k[x][y]+" ";
i++;x++;
}
if(i==q*w)break;
str=str+k[x][y]+" ";
y++;i++;
while(y<=w-a)
{
str=str+k[x][y]+" ";
i++;y++;
}
if(i==q*w)break;
str=str+k[x][y]+" ";
i++;x--;
while(x>a)
{
str=str+k[x][y]+" ";
i++;x--;
}
if(i==q*w)break;
str=str+k[x][y]+" ";
i++;y--;
while(y>a+1)
{
str=str+k[x][y]+" ";
i++;y--;
}
a++;
}
for(int c=0;c<str.length()-1;c++)
System.out.print(str.charAt(c));
}
}
方法2
import java.util.Scanner;
public class HuiNum
{
static String str="";
static int kk[][],i,j;
static boolean hh[][];
public static void main(String args[])
{
Scanner cn=new Scanner(System.in);
i=cn.nextInt();
j=cn.nextInt();
kk=new int[i][j];
hh=new boolean[i][j];
for(int q=0;q<i;q++)
for(int w=0;w<j;w++)
kk[q][w]=cn.nextInt();
Input(0,0,0);
}
public static void Input(int a,int s,int d)
{
while(true)
{
while(Check(s,d)) //口字 竖直向下 左边的
{
str=str+kk[s][d]+" ";
hh[s][d]=true;s++;a++;
}
if(s==i)s--;
d++;
while(Check(s,d)) //口字 水平向右 下面的
{
str=str+kk[s][d]+" ";
hh[s][d]=true;d++; a++;
}
if(d==j)d--;
s--;
while(Check(s,d)) //口子 竖直向上 靠右的
{
str=str+kk[s][d]+" ";
hh[s][d]=true;s--;a++;
}
if(s==-1)s=0;
d--;
while(Check(s,d)) //口字 水平向左 靠上的
{
str=str+kk[s][d]+" ";
hh[s][d]=true;d--; a++;
}
d++;s++;
if(a==i*j)break;
}
System.out.println(str);
}
public static boolean Check(int s,int d) //检查是否遍历过 主要用于判断拐弯处
{
if(s>=i||d>=j||s<0||d<0)
return false;
if(hh[s][d]==false)return true;
else return false;
}
}