首页 > 解决方案 > 零的外部框架

问题描述

我写了这段代码。出于某种原因,我得到了新矩阵,但原始矩阵的最后一个值似乎丢失了......

    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;
}

标签: javaarraysmultidimensional-array

解决方案


外部框架意味着您必须分别添加两行/列(左和右/上和下),因此您需要通过额外的行和列来增加新矩阵的大小。
将帧设置为 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;
}

推荐阅读