经典矩阵试题(一)-LMLPHP




一、回型矩阵

1、题目介绍

经典矩阵试题(一)-LMLPHP

2、思路讲解

回型矩阵就是顺时针输入1到n的数字,这个题的思路是,定义x方向y方向的移动的,首先是x不变y加1,然后x加1y不变,然后x不变y减1,最后x减1 y不变。
然后循环注意边界问题,便可。

3、代码实现

#include <iostream>
using namespace std;
int main() {
    int n;
    cin>>n;
    int dx[]={0,1,0,-1};
    int dy[]={1,0,-1,0};
    int ans[20][20]={0};
    for(int x=0,y=0,d=0,k=1;k<=n*n;k++)
    {
        ans[x][y]=k;
        int a=x+dx[d],b=y+dy[d];
        if(a<0 || a>=n || b<0 || b>=n || ans[a][b])
        {
            d=(d+1)%4;
            a=x+dx[d],b=y+dy[d];
        }
        x=a,y=b;
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
           cout<<ans[i][j]<<' ';
        }
        cout<<endl;     
    }
}

4、结果

经典矩阵试题(一)-LMLPHP


二、蛇型矩阵

1、题目介绍

经典矩阵试题(一)-LMLPHP

2、思路讲解

我们可以发现i+j = n-1的条件,再发现以i+j = n - 1为分界线,前面的斜线分别是i + j = n-2,i+j = n-3…后面的分别是i+j = n,i+j = n+1…以此类推,让count= i+j,count从0开始再进行累加,直到2 * n-2结束,count为奇数的时候是左下,偶数的时候右上。

3、代码实现

#include <iostream>
using namespace std;
int main() {
	int n;
	cin>>n;
	int ans[1000][1000]={0};
	int count=0;
	int sum=1;
	while(count<=n*2-2)
	{
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
			{
				if(i+j==count)
				{
					if(count%2==0)
					{
						ans[j][i]=sum++;
					}
					else 
					{
					ans[i][j]=sum++;
					}
				}
			}
		}
		count++;
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		{
			cout<<ans[i][j]<<' ';
		}
		cout<<endl;
	}
	return 0;
}

4、结果

经典矩阵试题(一)-LMLPHP


总结

11-08 08:33