我有一個二維數組更換的行和列所以它看起來像這樣經過:在2D陣列
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
你不能簡單地看到一個零,然後零/行。這意味着隨後的讀取將會看到你的zero'd行/列,並且你的矩陣將全部爲0(如你所見)。你需要跟蹤你讀完整個矩陣後看到的零點,然後返回並將它們歸零。 –
這就是我使用臨時數組的原因。 –
這是一個開始,但由於不通過將變量分配給另一個來複制數組,只會複製引用。只需要創建一個新陣列來追蹤零位就可能更容易。您可以使用一維數組,按行進行索引,存儲列的索引,然後從該列索引。 –