package java_study.JianZhiOffer;
import org.junit.Test;
import java.util.Scanner;
import java.util.stream.StreamSupport;
/**
* Created by ethan on 2015/6/29.
* 剑指offer No20顺时针打印矩阵
* 剑指offer中给出的答案在列输出的时候有个小bug在 if (col_start < col_end) ====》 if (col_start <= col_end)
* 这道题没难度主要考细节。
*/
public class No20顺时针打印矩阵 {
public static int[][] init() {
Scanner scanner = new Scanner(System.in);
int rows;
int cols;
System.out.println("请输入行数: ");
rows = scanner.nextInt();
System.out.println("请输入列数: ");
cols = scanner.nextInt();
int[][] arr = new int[rows][cols];
System.out.println("请输入" + rows * cols + "个整数");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = scanner.nextInt();
}
}
return arr;
}
public static void printClockWise(int[][] arr) {
if (arr == null) return;
int rows = arr.length;
int cols = arr[0].length;
int half_rows = (rows & 1) == 1 ? (rows >> 1) + 1 : rows >> 1;
int half_cols = (cols & 1) == 1 ? (cols >> 1) + 1 : cols >> 1;
int min = half_cols > half_rows ? half_rows : half_cols;
System.out.println(rows + " " + cols + " " + half_rows + " " + half_cols + " " + min);
for (int i = 0; i < min; i++) {
printCircle(arr, i, rows, cols);
}
}
// 避免漏行 和 重行
public static void printCircle(int[][] arr, int x, int rows, int cols) {
int row_start = x;
int row_end = rows - x - 1;
int col_start = x;
int col_end = cols - x - 1;
for (int i = col_start; i <= col_end; i++) {
System.out.print(arr[row_start][i] + " ");
}
if (col_start <= col_end)
for (int i = row_start + 1; i <= row_end; i++) {
System.out.print(arr[i][col_end] + " ");
}
if (row_start < row_end && col_start < col_end)
for (int i = col_end - 1; i >= col_start; i--) {
System.out.print(arr[row_end][i] + " ");
}
if (row_start < row_end && col_start < col_end-1)
for (int i = row_end - 1; i > row_start; i--) {
System.out.print(arr[i][col_start] + " ");
}
}
public static void print_arr(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] arr = init();
print_arr(arr);
printClockWise(arr);
}
}
顺时针打印矩阵
最新推荐文章于 2022-07-04 16:36:49 发布