ICPC:螺旋矩阵

题目描述:

一个n行n列的螺旋矩阵可由如下方法生成:
从矩阵的左上角(第1行第1列)出发,初始时向右移动;如果前方是未曾经过的格子,则继续前进,否则右转;重复上述操作直至经过矩阵中所有格子。根据经过顺序,在格子中依次填入1,2,3,...,n2,便构成了一个螺旋矩阵。
下图是一个n=4时的螺旋矩阵。

现给出矩阵大小n以及i和j,请你求出该矩阵中第i行第j列的数是多少。

输入:

输入共一行,包含三个整数 n,i,j,每两个整数之间用一个空格隔开,分别表示矩阵大小、待求的数所在的行号和列号。
1≤n≤30000,1≤i≤n,1≤j≤n

输出:

输出共一行,包含一个整数,表示相应矩阵中第i行第j列的数。

样例输出:

4 2 3

样例输出:

14
#include <bits/stdc++.h>

using namespace std;

long long int n;
long long int direction = 1;
long long int cnt=1;

void go(long long int &x, long long int &y, long long int &u, long long int &d, long long int &l, long long int &r)
{
    if (direction == 0)
    {
        direction = (1+direction)%4;
        cnt+=abs(u - y);
        y = u;
        l++;
    }
    else if (direction == 1)
    {
        direction = (1+direction)%4;
        cnt+=abs(r - x);
        x = r;
        u++;
    }
    else if (direction == 2)
    {
        direction = (1+direction)%4;
        cnt+=abs(d - y);
        y = d;
        r--;
    }
    else if (direction == 3)
    {
        direction = (1+direction)%4;
        cnt+=abs(l - x);
        x = l;
        d--;
    }


}

int main()
{
    long long int i,j;
    cin>>n;
    cin>>i>>j;
    long long int u = 1, d = n, l = 1, r = n;
    pair<long long int,long long int>pre_po = {1,1};
    pair<long long int,long long int>position = {1,1};
    long long int answer = 0;
    for(; ;)
    {
        pre_po = position;
        go(position.second,position.first,u,d,l,r);
//        cout<<"preposition:"<<pre_po.first<<" "<<pre_po.second<<endl;
//        cout<<"nowposition:"<<position.first<<" "<<position.second<<endl;
//        cout<<"cnt:"<<cnt<<endl;
//        cout<<"----------"<<endl;
        if(pre_po.first == position.first && position.first == i){
            if(position.second >= j && j >= pre_po.second){
                answer = cnt - (position.second - j);
                break;
             }
            else if(position.second <= j && j <= pre_po.second){
                answer = cnt - (j - position.second);
                break;
            }

        }
        else if(pre_po.second == position.second && position.second == j){
            if(position.first >= i && i >= pre_po.first){
                answer = cnt - (position.first - i);
                break;
            }
            else if(position.first <= i && i <= pre_po.first){
                answer = cnt - (i - position.first);
                break;
            }

        }
    }

    cout<<answer;



    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值