回形取数

蓝桥杯java

回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。

超时代码,更好理解该模拟过程

import java.util.Scanner;
public class DemoBasic25 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int r=in.nextInt();//r行
int l=in.nextInt();//l列
int[][] a=new int[r][l];
for(int i=0;i<r;i++) {
for(int j=0;j<l;j++) {
a[i][j]=in.nextInt();
}
}
int count =r*l;int i=0;int j=0;
while(count>0) {
while(i<r&&a[i][j]!=-1) {
System.out.print(a[i][j]+" ");
a[i][j]=-1;
i++;
count--;
}
i--;
j++;
while(j<l&&a[i][j]!=-1) {
System.out.print(a[i][j]+" ");
a[i][j]=-1;
j++;
count--;
}
j--;
i--;
while(i>=0&&a[i][j]!=-1) {
System.out.print(a[i][j]+" ");
a[i][j]=-1;
i--;
count--;
}
i++;
j--;
while(j>=0&&a[i][j]!=-1) {
System.out.print(a[i][j]+" ");
a[i][j]=-1;
j--;
}
j++;
i++;
}
in.close();

}

}

正确的代码

import java.util.Scanner;
public class DemoBasic255 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] a = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();

}

}
int tot = 0, x = -1, y = 0;
while (tot < m * n) {
while (x + 1 < m && a[x + 1][y] != -1) {
System.out.print(a[++x][y]+" ");
a[x][y] = -1;
++tot;
}
while (y + 1 < n && a[x][y + 1] != -1) {
System.out.print(a[x][++y]+" ");
a[x][y] = -1;
++tot;
}
while (x - 1 >= 0 && a[x - 1][y] != -1) {
System.out.print(a[--x][y]+" ");
a[x][y] = -1;
++tot;
}

while (y - 1 >= 0 && a[x][y - 1] != -1) {
System.out.print(a[x][--y]+" ");
a[x][y] = -1;
++tot;
}
}
sc.close();

}

}

该代码减少了需要i++后又i--的步骤

posted @ 2021-04-14 21:48  HYLboke  阅读(134)  评论(0)    收藏  举报