BASIC-25取回形数

资源限制

时间限制: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.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;

 public class Main {
     public static void main(String[] args) throws IOException {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String[] str = br.readLine().split(" ");
         int n = Integer.parseInt(str[0]);
         int m = Integer.parseInt(str[1]);
         int[][] num = new int[n][m];
         for(int i = 0; i < n; i++){
             String[] t = br.readLine().split(" ");
             for(int j = 0; j < m; j++){
                 num[i][j] = Integer.parseInt(t[j]);
             }
         }

         int[] memory = new int[n*m];        //存储每一步取到的数
         loopGetNum(n,m,num,memory);

         for(int i = 0; i < memory.length; i++){
             System.out.print(memory[i]+" ");
         }

     }

     private static void loopGetNum(int n, int m, int[][] num, int[] memory) {
         int row = 0;          
         int col = 0;          
         int cirNum = 0;       
         int total = n * m;   

         for(int i = 0; i < total; i++){
             if(row < n && col == cirNum){                //第一列
                 memory[i] = num[row][col];
                 row++;
             }else if(row == n && col < m-1){            //最后一行
                 col++;
                 memory[i] = num[row-1][col];
             }else if(row-1 > cirNum && col == m-1){        //最后一列
                 row--;
                 memory[i] = num[row-1][col];
             }else if(row-1 == cirNum && col > cirNum){    //第一行
                 col--;
                 memory[i] = num[row-1][col];
                 if(row-1 == cirNum && col == cirNum+1){    //若到第一行第二个数字,则缩小矩阵行列范围,形成子矩阵
                     cirNum++;
                     n = n-1;
                     m = m-1;
                     row = cirNum;
                     col = cirNum;
                 }

             }
         }
    }
 }
发布了82 篇原创文章 · 获赞 10 · 访问量 6218

猜你喜欢

转载自blog.csdn.net/qq_41705207/article/details/105339700