日期:2014-05-20  浏览次数:20739 次

请教一个算法,怎样给二维数组外面套一圈0
请教算法,有一二维数组 如下
1 2 3
4 5 6
7 8 9
输出
0 0 0 0 0
0 1 2 3 0
0 4 5 6 0
0 7 8 9 0
0 0 0 0 0
请教一下算法应该怎么写.谢谢大家

------解决方案--------------------
Java code

//刚写的,但只能转化等列的数组,调试通过比较符合你的要求
public class Zero{
    /**
     * 将一个等列数的二维数组转换成周围有一圈零的二维数组
     * @param a 待转换数组
     * @return 转换后的数组
     */
    public int [][] toZero(int [][] a){
        int [][] newArray =new int[a.length+2][a[0].length+2];
        for(int first=0;first<a[0].length+2;first++){
            newArray[0][first]=0;
        }        
        for(int i=0;i<a.length;i++){
            newArray[i+1][0]=0;
            for(int j=0;j<a[i].length;j++){
                newArray[i+1][j+1]=a[i][j];            
            }
            newArray[i+1][a[i].length+1]=0;
        }
        return newArray;    
    }
    /**
     * 打印数组
     * @param a 待打印的数组
     */
    public void print(int[][] a){

        for(int i=0;i<a.length;i++){
            for(int j=0;j<a[i].length;j++){
                System.out.print(a[i][j]);
            }System.out.println();
        }
    }
    public static void main(String [] args){
        Zero z = new Zero();
        //待转换的数组
        int [][] array ={
                {1,2,3},
                {4,5,6},
                {7,8,9},
            };
        z.print(z.toZero(array));//转换后打印    
    }
}
//打印结果:
//00000
//01230
//04560
//07890
//00000

------解决方案--------------------
那个,我最先贴的那个有些问题,调试了一下,重新贴一次。


Java code
public class Test {
    public static void main(String[] args) {
        final int ROW = 3;
        final int COL = 3;
        int m = 0;
        int k = 0;
        for (int i = 0; i <= ROW + 1; i++) {
            for (int j = 0; j <= COL + 1; j++) {
                if ((i == 0) || (j == 0) || (i == ROW + 1) || (j == COL + 1)) {
                    m = 0;
                } else {
                    k++;
                    m = k;
                }
                System.out.print(m + ((j == COL + 1) ? "\n" : " "));
            }
        }
    }
}