[BASIC-25] 回形取数

来源:互联网 发布:知行天下品牌策划 编辑:程序博客网 时间:2024/06/05 07:16

基础练习 回形取数  
时间限制:1.0s   内存限制:512.0MB
问题描述
  回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转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
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {int m = scanner.nextInt();int n = scanner.nextInt();int[][] flag = new int[m][n];// 标记路径int[][] nums = new int[m][n];// 记录数据for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {nums[i][j] = scanner.nextInt();}}int count = m * n;int i = 0, j = 0;while (count > 0) {while (i < m && flag[i][j] == 0) {System.out.print(nums[i][j]);System.out.print(--count == 0 ? "\r\n" : " ");flag[i][j] = 1;i++;}i--;j++;while (j < n && flag[i][j] == 0) {System.out.print(nums[i][j] + " ");System.out.print(--count == 0 ? "\r\n" : " ");flag[i][j] = 1;j++;}j--;i--;while (i > -1 && flag[i][j] == 0) {System.out.print(nums[i][j] + " ");System.out.print(--count == 0 ? "\r\n" : " ");flag[i][j] = 1;i--;}i++;j--;while (j > -1 && flag[i][j] == 0) {System.out.print(nums[i][j] + " ");System.out.print(--count == 0 ? "\r\n" : " ");flag[i][j] = 1;j--;}j++;i++;}}}}

0 0
原创粉丝点击