稀疏矩阵的验证

来源:互联网 发布:ubuntu 16.04 ed2k 编辑:程序博客网 时间:2024/05/21 15:48

package arithmetic;
/**
 *
 * @author pdw
 *  模拟稀疏矩阵的存储
    原理:遍历将不是0的位置的值取出来放入到一个新的矩阵之中
                   新的矩阵的 0列表示的是该数字所在的行
                 1列表示的是该数字所在的列
                 2列表示的是该数字本身的值
          
 */
public class SparseArray {

 public static void main(String[] args) {
      int src[][]=
      {
        {0,0,0,0,0,0,0},
        {0,3,0,0,0,0,0},
        {0,0,0,0,0,0,0},
        {1,4,0,0,0,0,0},
        {0,0,7,0,0,0,0},
        {0,0,0,0,0,5,0},
        {0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0}
      };
  //定义一个新数组
       int des[][]=new int[10][3];
     //定义一个指针位置
       int index=0;
      //扫描将值放入到新数组之中
     for(int row=0;row<src.length;row++)
      {
       for(int col=0;col<src[0].length;col++)
       {
        if(src[row][col]!=0)
        {
         index++;
         des[index][0]=row;
         des[index][1]=col;
         des[index][2]=src[row][col];
        
        }
       }
      }
      des[0][0]=src.length;
      des[0][1]=src[0].length;
      des[0][2]=index;
      //打印
   for(int i=0;i<=index;i++)
   {
    for(int j=0;j<3;j++)
    {
     System.out.print(" "+des[i][j]);
    }
    System.out.println(" ");
   }
 }

}

原创粉丝点击