ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

(蓝桥杯)试题 算法训练 回形取数

2021-09-19 09:29:51  阅读:187  来源: 互联网

标签:count 取数 leftRow matrix int 蓝桥 ++ -- 回形


试题 算法训练 回形取数

  • 资源限制
  • 时间限制: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 int count  = 0 ;
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in) ;
        int m = input.nextInt() ;
        int n = input.nextInt() ;
        int [][] matrix = new int [m][n] ;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                matrix[i][j] = input.nextInt() ;
            }
        }
        int leftRow = 0, leftColumn = 0, rightRow = m-1, rightColumn = n-1 ;
        while((leftRow <= rightRow) && (leftColumn <= rightColumn)){
            int r = leftRow , c = leftColumn ;
            while(r <= rightRow){
                    System.out.print(matrix[r++][c] + " ") ;
                    count ++ ;
            }
            if(count == m*n){
                break ;
            }
                r = rightRow;
                c++;
            while(c <= rightColumn){
                System.out.print(matrix[r][c++] + " ") ;
                count ++ ;
            }
            if(count == m*n){
                break ;
            }
                c = rightColumn;
                r--;
            while(r >= leftRow){
                System.out.print(matrix[r--][c] + " ") ;
                count ++ ;
            }
            if(count == m*n){
                break ;
            }
                r = leftRow;
                c--;
            while(c > leftColumn){
                System.out.print(matrix[r][c--] + " ") ;
                count ++ ;
            }
            if(count == m*n){
                break ;
            }
            leftRow ++;
            leftColumn ++ ;
            rightRow -- ;
            rightColumn -- ;
        }
    }
}

标签:count,取数,leftRow,matrix,int,蓝桥,++,--,回形
来源: https://blog.csdn.net/nuist_NJUPT/article/details/120377285

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有