我已经编写了螺旋打印矩阵的代码。
我的遍历是正确的,但我无法提出矩阵中层数的结束条件。
请在下面查看我的代码
当我将层数硬编码为 2 时,我得到了预期的输出,因为我事先知道矩阵。如何用某些东西替换 while 循环中的条件,以便它适用于所有矩阵。
public class IterativeSpiral
{
public static void main(String[] args)
{
char[][] a = {
{'a','b','c','d'},
{'l','m','n','e'},
{'k','p','o','f'},
{'j','i','h','g'}
};
fun(a,4,4);
}
static void fun(char[][] a, int rows, int cols)
{
int count = 0;
//this condition in while loop needs to be replaced
while(count < 2)
{
System.out.println("Layer"+count);
for(int i = count;i<cols-count;i++)
System.out.print(a[count][i]);
for(int i = count+1;i<rows-count;i++)
System.out.print(a[i][cols-count-1]);
for(int i = cols-count-2;i>=count;i--)
System.out.print(a[rows-count-1][i]);
for(int i = rows-count-2;i>count;i--)
System.out.print(a[i][count]);
count++;
System.out.println("");
}
}
}
我试图找到一个结束条件
- 我想到的任何结束条件,我都会遇到一个反例,它不像 2*5(更多列)或 5*2(更多行)矩阵那样工作。
- 我能想到的唯一结束条件是计算每个 for 循环之后的元素数,并在它等于 rows*cols 时从 while 循环中中断。然而,我不想这样做。我正在使用代码中的变量寻找结束条件。