我写了这段代码。出于某种原因,我得到了新的矩阵,但原始矩阵的最后一个值似乎缺失了......
public static char[][] Frame_of_zeros(char[][]a)//builds an external frame of zeroes
{
char[][]c3=new char[a.length+1][a[0].length+1];
for(int i=0,j=0;i<c3.length;i++)//left column is composed of zeroes
{
c3[i][j]='0';
}
for(int j=0,i=0;j<c3[0].length;j++)//upper row of zeroes
{
c3[i][j]='0';
}
for(int i=c3.length-1,j=0;j<c3[0].length;j++)//most lower row composed of zeroes
{
c3[i][j]='0';
}
for(int i=0,j=c3[0].length-1;i<c3.length;i++)//right column is composed of zeroes
{
c3[i][j]='0';
}
for(int i=1,k=0;i<c3.length-1&&k<a.length;i++,k++)//i for the modified and k is the original
{
for(int j=1,l=0;j<c3[0].length&&l<a[0].length-1;j++,l++)//j for the modified and l is the original
{
c3[i][j]=a[k][l];
}
}
return c3;
}
答案 0 :(得分:0)
外部框架意味着您必须分别添加两行/每列(左侧和右侧/上部和下部),因此您需要通过额外的行和列来增加新矩阵的大小。
用于将帧设置为0的循环很好
在最后一个内部循环中,您将初始矩阵的缩小大小设置为条件,而不是外循环中的新大小。
public static char[][] Frame_of_zeros(char[][]a)//builds an external frame of zeroes
{
char[][]c3=new char[a.length+2][a[0].length+2];
for(int i=0,j=0;i<c3.length;i++)//left column is composed of zeroes
{
c3[i][j]='0';
}
for(int j=0,i=0;j<c3[0].length;j++)//upper row of zeroes
{
c3[i][j]='0';
}
for(int i=c3.length-1,j=0;j<c3[0].length;j++)//most lower row composed of zeroes
{
c3[i][j]='0';
}
for(int i=0,j=c3[0].length-1;i<c3.length;i++)//right column is composed of zeroes
{
c3[i][j]='0';
}
for(int i=1,k=0;i<c3.length-1 && k<a.length;i++,k++)//i for the modified and k is the original
{
for(int j=1,l=0;j<c3[0].length-1 && l<a[0].length;j++,l++)//j for the modified and l is the original
{
c3[i][j]=a[k][l];
}
}
return c3;
}