洛谷P2239 螺旋矩阵

本文介绍了一种通过层次遍历方式,在矩阵中寻找指定位置元素值的算法实现。该算法将矩阵视为多层结构,通过去除外层的方式找到目标位置,并根据不同情况计算其值。适用于求解二维数组中特定坐标对应的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门

分析:将整个矩阵看成 “回” 形状的分层结构,然后进行去层处理,使得要求得 \((i,j)\) 处于最外层,然后再分情况讨论。最外面的一层共有数: $ 4 * n - 4 $ . 第二层共有数: 4n-4 -8
假设 $ (i,j) $ 外共有 $ x $ 层,则外层所有的数为: $ ans=4
nx-4x*x $ 。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std ;

inline int read () {
    int f = 1 , x = 0 ;
    char ch = getchar () ;
    while(ch > '9' || ch < '0')  {if(ch == '-')  f = -1 ; ch = getchar () ;} 
    while(ch >= '0' && ch <= '9') {x = (x << 1) + (x << 3) + ch - '0' ; ch = getchar () ;}
    return x * f ;
}

int n , x , y ;
int t , ans ;

int main () {
    n = read () ;
    x = read () ; y = read () ;
    t = min(x - 1 , n - x) ;
    t = min(t , min(y - 1 , n - y) ) ;
    ans = 4 * n * t - 4 * t * t ;
    
    if(x - t == 1)
        ans += y - t ;
    else if(x + t == n)
        ans += 3 * n - 5 * t - 1 - y ;
    else if(y - t == 1) 
        ans += 4 * n - 7 * t - 2 - x ;
    else ans += n - 3 * t + x - 1 ;
    printf("%d\n" , ans) ;
    return 0 ;
}

转载于:https://www.cnblogs.com/Stephen-F/p/10588108.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值