簡體   English   中英

替換二維數組中的行和列

[英]Replacing rows and columns in a 2d array

我有一個二維數組:

1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1

我必須編寫一個程序來檢查數組中是否存在0,如果是,則將行和列替換為0,因此它如下所示:

0 0 0 0
1 0 1 1
1 0 1 1
1 0 1 1

到目前為止,這是我的代碼:

public class Run {


    public static void main(String[] args){
        //defining 2d array
        int[][] m = { {1,0,1,1}, 
                      {1,1,1,1},
                      {1,1,1,1},
                      {1,1,1,1}}; 
        int[][] newArray = zero(m);
        //looping through the array to get rows and columns for the array
        //rows
        for (int i = 0; i < m.length; i++) {
            //columns
            for (int j = 0; j < m[0].length; j++) { 
                //check if the integer is the last in the row
                if(j== m.length-1){
                    //print the rows and columns of the array(no space)
                    System.out.print(newArray[i][j]);
                }else{
                    //print the rows and columns of the array(w/ space)
                    System.out.print(newArray[i][j] + " ");
                }
            }
            //new line for the new row
        System.out.println("");
        }
    }

    //checks if there is a zero in the row
    public static int[][] zero(int[][] m) {
        //defining row length and column length
        int rows = m.length;
        int columns = m[0].length;
        int[][] tempArray = m;

        //looping through the array to get rows and columns
        //rows
        for (int i = 0; i < rows; i++) {
            //columns
            for (int j = 0; j < columns; j++) {
                //if the number is 0 loop through that row and column again and change everything to 0 
                if(m[i][j] == 0){
                    //columns in that row
                    for(int l = 0; l < rows; l++)
                    {
                        tempArray[l][j] = 0;
                    }
                    //rows in that column
                    for(int l = 0; l < columns; l++)
                    {
                        tempArray[i][l] = 0;
                    }
                }
            }
        }

        //returning the updated array
        return tempArray;
}

}

當我運行我的代碼時,它返回:

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

但是當我取出其中一個時:

    //columns in that row
for(int l = 0; l < rows; l++)
{
    tempArray[l][j] = 0;
}

要么

    //rows in that column
for(int l = 0; l < rows; l++)
{
    tempArray[l][j] = 0;
}

它返回:

0 0 0 0
1 1 1 1
1 1 1 1
1 1 1 1

要么

1 0 1 1
1 0 1 1
1 0 1 1
1 0 1 1

問題是線

int[][] tempArray = m;

這使tempArraym成為完全相同的實例 ,因此實際上您只有一個矩陣。

相反,你應該做

int[][] tempArray = new int[rows][columns];
for (int i = 0; i < rows; i++)
    for (int j = 0; j < columns; j++)
        tempArray[i][j] = m[i][j];

您在循環中檢測到0,然后去修改數據並繼續循環,現在循環將看到更多的零,因此設置了更多的零。

一旦發現0,就應該中斷,或者將檢測與“重寫”分開-先進行所有檢測,然后再進行所有重寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM