5

#yyds干货盘点# 名企真题专题:顺时针打印数字矩阵

 1 year ago
source link: https://blog.51cto.com/u_15488507/5981160
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 名企真题专题:顺时针打印数字矩阵

精选 原创

97的风 2022-12-30 18:18:20 博主文章分类:面试题 ©著作权

文章标签 java 顺时针 i++ 文章分类 Java 编程语言 阅读数340

1.简述:

描述

给定一个数字矩阵,请设计一个算法从左上角开始顺时针打印矩阵元素

输入描述:

输入第一行是两个数字,分别代表行数M和列数N;接下来是M行,每行N个数字,表示这个矩阵的所有元素;当读到M=-1,N=-1时,输入终止。

输出描述:

请按逗号分割顺时针打印矩阵元素(注意最后一个元素末尾不要有逗号!例如输出“1,2,3”,而不是“1,2,3,”),每个矩阵输出完成后记得换行

示例1
3 3
1 2 3
4 5 6
7 8 9
-1 -1
1,2,3,6,9,8,7,4,5

2.代码实现:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(br.ready()) {
String[] s = br.readLine().split(" ");
int m = Integer.parseInt(s[0]);
int n = Integer.parseInt(s[1]);
if(m == -1 && n == -1) break;
int[][] matrix = new int[m][n];
for(int i = 0; i < m; i++) {
String[] temp = br.readLine().split(" ");
for(int j = 0; j < n; j++)
matrix[i][j] = Integer.parseInt(temp[j]);
}
printMatrix(matrix, m, n);
}
}
private static void printMatrix(int[][] mat, int rows, int cols) {
if(mat == null || rows == 0 || cols == 0) return;
StringBuilder sb = new StringBuilder();
int min = Math.min(rows, cols);
for(int s = 0; 2*s < min; s++) {
int endRow = rows-1-s;
int endCol = cols-1-s;
for(int j = s; j <= endCol; j++) //直接打印第一行
sb.append(mat[s][j]+",");
if(endRow > s) { //存在第二行的条件
for(int i = s+1; i <= endRow; i++)
sb.append(mat[i][endCol]+",");
if(endCol > s) { //存在第三行的条件
for(int j = endCol-1; j >= s; j--)
sb.append(mat[endRow][j]+",");
if(endRow > s+1) { //存在第四行的条件
for(int i = endRow-1; i > s; i--)
sb.append(mat[i][s]+",");
}
}
}
}
//打印
System.out.println(sb.substring(0,sb.length()-1));
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK