java 蛇形矩阵,JAVA:如何创建一个蛇形矩阵

Hi I am trying to create a matrix on the console using 2D array. The idea is that the output should look like this one :

1|8|9 |16

2|7|10|15

3|6|11|14

4|5|12|13

Is there any one who has an idea how it can be done?

解决方案

Few things you can guess from the matrix: -

First, you have to traverse all rows of a columns first before moving to the next column

Second, you need to alternate between downwards and upwards direction on each iteration

So, you would need two nested for loop, for iterating through rows for a particular column. One will go from row 0 to max - 1, and the next will go from row = max - 1 to 0.

Now, to alternate the iteration direction, you can use a boolean variable, and toggle it after each iteration of inner loop finishes.

Each loop needs to be enclosed inside an if-else. Both of them will be executed on a certain condition. If boolean downwards = false;, then loop moving upwards will be executed and vice-versa.

On each iteration, fill the current cell with an integer counter, that you would have to initialize with 1, and increment it after each fill.

Pseudo code : -

// Initialize variables row, col, and count = 1

boolean goDown = true;

int[][] matrix = new int[row][col]; // declare matrix

for i = 0 to col:

if (goDown)

for j = 0 to row: // Move in downwards direction

assign count++ to matrix[j][i]

// assign to `[j][i]` because, we have to assign to rows first

goDown = false; // Toggle goDown

else

for j = row - 1 to 0: // Move in upwards direction

assign count++ to matrix[j][i]

goDown = true; // toggle goDown

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值