У меня есть 2d массив:Замена строк и столбцов в 2d массив
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
Вы не можете просто увидеть нуль и затем обнулить строку/столбец. Это означает, что последующие чтения будут видеть вашу нулевую строку/col, и ваша матрица станет все 0 (как вы видели). Вам нужно следить за нулем, который вы видите после того, как прочитаете всю матрицу, затем вернитесь и обнулите их. –
Вот почему я использовал временный массив. –
Это начало, но поскольку массивы не копируются просто путем назначения переменной другой, которая только копирует ссылку. Вероятно, было бы проще просто создать новый массив для отслеживания нулевых позиций. Вы можете использовать для этого массив 1D, индексированный по строке, сохраняющий индекс столбца, а затем нуль от него. –