螺旋矩阵算法解决

在这里插入图片描述
在这里插入图片描述
对于这个题,我们可以依据螺旋矩阵的遍历方式,给矩阵赋值
以下是代码:

#include <iostream>
#include <cstring>
#include <map>
using namespace std;
int main()
{   int n,m,r,c;
    cin>>n>>m>>r>>c;
    map<int ,map<int,int> >store;
    int sum=n*m;
    int row=0,col=0,cnt=1;
    store[row][col]=1;
    while(cnt<sum)
    {   //向右走 
    	while(col+1<m&&!store[row][col+1])
    	{
    		store[row][++col]=++cnt;
    		
		}
    	
    	 //向下走 
    	while(row+1<n&&!store[row+1][col])
    	{store[++row][col]=++cnt;
    	
		}	
    	 //向左走 
    	while(col>0&&!store[row][col-1])
    	{
    		store[row][--col]=++cnt;		
		} 	
    	//向上走 
    	while(row-1>0&&!store[row-1][col])
    	{
    		store[--row][col]=++cnt;
    		
		}		
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
		cout<<store[i][j]<<" ";	
		}
		cout<<endl;
		}	
	   cout<<store[r-1][c-1];
	return 0;
}

下面是我从网上找的别人写法,特别虎!

#include<iostream>
using namespace std;
struct circle {
    int x1, x2;
    int y1, y2;
};
int main()
{
    int n, m;
    int r, c;
    cin >> n >> m;
    cin >> r >> c;
    int total = n * m;
    int a = n / 2;
    if (n % 2 != 0)
    {
        a++;
    }
    circle q[1001];
    int x1 = 1, x2 = n;
    int y1 = 1, y2 = m;
    for (int i = 0; i < a; i++)
    {
        q[i].x1 = x1;
        q[i].x2 = x2;
        q[i].y1 = y1;
        q[i].y2 = y2;
        x1++;
        x2--;
        y1++;
        y2--;
    }
    int num = 0;
    for (int i = a - 1; i >= 0; i--)
    {
        if (r >= q[i].x1 && r <= q[i].x2 && c >= q[i].y1 && c <= q[i].y2)
        {
            for (int j = 0; j < i; j++)
            {
                num = num + (q[j].y2 - q[j].y1 + 1) * 2 + (q[j].x2 - q[j].x1 - 1) * 2;

            }
            if (r == q[i].x1)
            {
                num = num + c - q[i].y1 + 1;
            }
            else if (c == q[i].y2)
            {
                num = num + (q[i].y2 - q[i].y1 + 1) + r - q[i].x1;
            }
            else if (r == q[i].x2)
            {
                num = num + (q[i].y2 - q[i].y1 + 1) + (q[i].x2 - q[i].x1 - 1) + q[i].y2 - c + 1;
            }
            else
            {
                num = num + (q[i].y2 - q[i].y1 + 1) * 2 + (q[i].x2 - q[i].x1 - 2) + q[i].x2 - r + 1;
            }
            cout << num;
            return 0;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值