problem:
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
for example:
A matrix of order 3X3 contains elemennts like
124
037
598
after performing algorithm out put will be
024
000
098
solution:
package logics;
public class matrixProblem {
public static void main(String []a)
{
int [][]data=new int[][]{{1,2,4},{0,3,7},{5,9,8}};
System.out.print("Before completing task \n");
printdata(data);
getdata(data);
}
public static void getdata(int [][] mat)
{
int rowlength=mat.length;
int collength=mat[0].length;
int row[]=new int[rowlength];
int col[]=new int[collength];
for(int i=0;i<rowlength;i++)
{
for(int j=0;j<collength;j++)
{
if(mat[i][j]==0)
{
row[i]=1011;//am setting reference as 1011 where i need to set 0 .
col[j]=1011;
}
}
}
for(int i=0;i<rowlength;i++)
{
for(int j=0;j<collength;j++)
{
if(row[i]==1011 || col[j]==1011)
{
mat[i][j]=0;
}
}
}
//printing matrix
System.out.print("After completing task \n");
printdata(mat);
}
public static void printdata(int [][]data)
{
for(int i=0;i<data.length;i++)
{
for(int j=0;j<data[0].length;j++)
{
System.out.print(data[i][j]);
}
System.out.println();
}
}
}//class
output:
------------------------------------------------
Before completing task
124
037
598
After completing task
024
000
098
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
for example:
A matrix of order 3X3 contains elemennts like
124
037
598
after performing algorithm out put will be
024
000
098
solution:
package logics;
public class matrixProblem {
public static void main(String []a)
{
int [][]data=new int[][]{{1,2,4},{0,3,7},{5,9,8}};
System.out.print("Before completing task \n");
printdata(data);
getdata(data);
}
public static void getdata(int [][] mat)
{
int rowlength=mat.length;
int collength=mat[0].length;
int row[]=new int[rowlength];
int col[]=new int[collength];
for(int i=0;i<rowlength;i++)
{
for(int j=0;j<collength;j++)
{
if(mat[i][j]==0)
{
row[i]=1011;//am setting reference as 1011 where i need to set 0 .
col[j]=1011;
}
}
}
for(int i=0;i<rowlength;i++)
{
for(int j=0;j<collength;j++)
{
if(row[i]==1011 || col[j]==1011)
{
mat[i][j]=0;
}
}
}
//printing matrix
System.out.print("After completing task \n");
printdata(mat);
}
public static void printdata(int [][]data)
{
for(int i=0;i<data.length;i++)
{
for(int j=0;j<data[0].length;j++)
{
System.out.print(data[i][j]);
}
System.out.println();
}
}
}//class
output:
------------------------------------------------
Before completing task
124
037
598
After completing task
024
000
098
Không có nhận xét nào:
Đăng nhận xét