行列をらせん状に出力するコードを書きました。
トラバーサルは正しいのですが、マトリックス内のレイヤー数の終了条件を思い付くことができません。
以下の私のコードを見てください
事前にマトリックスを知っているので、層の数を 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 ループから抜け出すことです。しかし、私はこれをしたくありません。コード内の変数を使用して何かで終了条件を探しています。