转圈打印矩阵~~


下面附上程序,欢迎各位前来讨论:

package jian_zhi_offer; 



public class code29_PrintMatrixClockWisely {
public static void main(String args[]) {
int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
printMatrix(arr);
}


/* 这个函数主要是用来调用printEdge这个函数的,还有就是让转圈往里边走 */
public static void printMatrix(int arr[][]) {
if (arr == null)
return;
int row1 = 0;
int col1 = 0;
/* 取得矩阵的右下角坐标,记住,别写错了 */
int row2 = arr.length - 1;
int col2 = arr[0].length - 1;
/* 两个同时满足才可以 */
/* 转圈停止的条件~ */
while (col1 <= col2 && row1 <= row2) {
/* 调用printEdge,同时转圈往里边走 */
printEdge(arr, row1++, col1++, row2--, col2--);
}
}


/* 逻辑主要实现部分:分三种情况:只有一行,只有一列,有多行和多列 */
public static void printEdge(int arr[][], int row1, int col1, int row2, int col2) {
/* 只有一行或者只有一列的情况下,直接打印出来即可 */
if (row1 == row2) {
for (; col1 <= col2; col1++) {
System.out.print(arr[row1][col1] + " ");
}
} else if (col1 == col2) {
for (; row1 <= row2; row1++) {
System.out.print(arr[row1][col1] + " ");
}
}
/* 有多行和多列的时候,定义两个变量,来遍历整个edge元素 */
else {
int curR = row1;
int curC = col1;
while (curC != col2)
System.out.print(arr[curR][curC++] + " ");
while (curR != row2)
System.out.print(arr[curR++][curC] + " ");
while (curC != col1)
System.out.print(arr[curR][curC--] + " ");
while (curR != row1)
System.out.print(arr[curR--][curC] + " ");
}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值