• 返回一个二维循环数组中最大子矩阵的和


    设计思路

    和一维循环数组思路相仿,循环N次,每次将第一列的数移到最后一列,新建一个相同规格的二维数组来存放新矩阵,将之前写的求二维数组最大子矩阵的和的算法稍作修改,添加一个循环即可满足要求。

    源程序代码

    #include<iostream>

    #include <cstdlib>

    #include <ctime>

    using namespace std;

    #define M 4

    #define N 4

     

    void main()

    {

         int a[M][N],aa[M][N],i,j,b,c,z;

         cout<<"请输入数值范围:"<<endl;

         cin>>b>>c;

         cout<<"生成二维数组为:"<<endl;

         srand(unsigned(time(0)));

         for(i=0;i<M;i++)

         {

             for(j=0;j<N;j++)

             {

                  a[i][j]=rand()%(c-b+1)+b;

                  cout<<a[i][j]<<" ";

             }

             cout<<endl;

         }

         int sum,s[100],k=0,o=-1000,p=-1000,q=-1000;

         for(j=0;j<N;j++)

         {

             s[j]=0;

         }

         for (int lun=0;lun<N;lun++)

         {

             for (int lunm=0;lunm<M;lunm++)

             {

                  for (int lunn=0;lunn<N;lunn++)

                  {

                       if (lunn+lun<N)

                       {

                           aa[lunm][lunn]=a[lunm][lunn+lun];

                       }

                       else

                           aa[lunm][lunn]=a[lunm][lunn+lun-N];

                  }

             }

             for(int ii=0;ii<M;ii++)

             {

                  while(k+ii<M)

                  {

                       for(j=0;j<N;j++)

                       {

                           s[j]=s[j]+aa[k+ii][j];

                       }

                       for (i=0;i<N;i++)

                       {

                           for (j=i;j<N;j++)

                           {

                                sum=0;

                                for (z=i;z<=j;z++)

                                {

                                     sum=sum+s[z];

                                }

                                if (sum>o) o=sum;

                           }

                           if (o>p)

                           {

                                p=o;

                           }

                       }

                       k++;

                  }

                  if (p>q)

                  {

                       q=p;

                  }

                  k=0;

                  for(j=0;j<N;j++)

                  {

                       s[j]=0;

                  }

             }

         }

         cout<<"子矩阵最大值为:"<<q<<endl;

    }

    运行结果截图

    编程总结

    在原代码的基础上修改代码可以节省许多时间,所以要能够熟练的读懂代码、修改代码。

  • 相关阅读:
    多层结构中,事务的运用。
    A private conversation
    Sql Server 日志清理 (数据库压缩方法)
    Basic of Ajax
    Persin Buttons
    不知为什么无缘无故加到了一个“邯郸.net俱乐部”,想退出,找不到入口.....
    Wokflow designer not working when openning workflow in nonworkflow VS 2005 project
    GridView中如何取得隐藏列的值?
    Error: cannot obtain value
    Too late
  • 原文地址:https://www.cnblogs.com/BUANG/p/4448774.html
Copyright © 2020-2023  润新知