注册 登录
编程论坛 C++教室

关于对二维矩阵进行螺旋化,写出来了,但是运行不了

ruifate 发布于 2012-07-22 23:24, 350 次点击
题目就是  7    6  5   16
          8    11 4   15
          9    2  3   14
          10   11 12  13
下面是我写的奇数矩阵的程序,编译没问题,一运行就显示已关闭,我逐过程调试断点找出来了,但是我进行人工演算发现并没错误,求指教。断点用红色写出。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int N;
    cout<<"PLZ enter a N";
    cin>>N;
    int **a = new int*[N];
    for(int i=0;i<N;i++)
    {
         a[i]=new int[N];
    }
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<N;j++)
            a[i][j]=i*N+j+1;
    }
    if(N%2==0)
    {
    }
    else
    {
        int m,n,k,count=1;
        m=n=N/2+1;
        a[m][n]=1;
        k=(N-1)/2;
        for(int i=1;i<=k;i++)//3次循环,下,右,上,左
        {
            for(int x=1;x<=2*i-1;x++)//下循环;
            {
                m=m+1;
                count++;
                a[m][n]=count;    注意是蓝色的循环已经运行一次,第二次循环才中断的,显示为内存写入异常
            }
            for(int y=1;y<=2*i-1;y++)//右循环
            {
                n=n+1;
                count++;
                a[m][n]=count;
            }
            for(int z=1;z<=2*i;z++)
            {
                m=m-1;
                count++;
                a[m][n]=count;
            }
            for(int x=1;x<=2*i;x++)
            {
                n=n-1;
                count++;
                a[m][n]=count;
            }
        }
        for(int x=1;x<=N-1;x++)
        {
            m=m+1;
            count++;
            a[m][n]=count;
        }
    }
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<N;j++)
            cout<<setw(3)<<a[i][j];
        cout<<endl;
    }
    for(int x=0; x<N; x++)
    {
        delete []a[x];
    }
    delete[] a;
    return 0;

}
0 回复
1