牛客堂常见面试题精讲(一)2

转圈打印矩阵的算法思想:

package com.zhao.niuke;

public class Problem_01_PrintMatrixSpiralOrder {
	public static void spiralOrderPrint(int[][] matrix) {
		int tR = 0;//左上角行标(起始坐标)
		int tC = 0;//列标
		int dR = matrix.length - 1;//右下角行标(终止坐标)
		int dC = matrix[0].length - 1;//右下角列标
		while (tR <= dR && tC <= dC) {//循环终止的条件
			printEdge(matrix, tR++, tC++, dR--, dC--);//开始打印
		}
	}
	public static void printEdge(int[][] m, int tR, int tC, int dR, int dC) {
		if (tR == dR) { // 子矩阵只有一行时
			for (int i = tC; i <= dC; i++) {
				System.out.print(m[tR][i] + " ");
			}
		} else if (tC == dC) { // 子矩阵只有一列时
			for (int i = tR; i <= dR; i++) {
				System.out.print(m[i][tC] + " ");
			}
		} else { // 一般情况
			int curC = tC;
			int curR = tR;
			while (curC != dC) {
				System.out.print(m[tR][curC] + " ");
				curC++;
			}
			while (curR != dR) {
				System.out.print(m[curR][dC] + " ");
				curR++;
			}
			while (curC != tC) {
				System.out.print(m[dR][curC] + " ");
				curC--;
			}
			while (curR != tR) {
				System.out.print(m[curR][tC] + " ");
				curR--;
			}
		}
	}
	public static void main(String[] args) {
		int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
				{ 13, 14, 15, 16 } };
		spiralOrderPrint(matrix);//转圈打印矩阵开始
	}
}
/*
 * 如何实现转圈打印矩阵
 * 思路就是找准坐标移动,先从左上角第一个坐标移动打印开始
 * 1 2 3 4
 * 5 6 7 8 
 * 9 10 11 12
 * 13 14 15 16
 */
详细讲解如图所示:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值