O(1)得到螺旋矩阵的值

 

 

LL ind(LL x, LL y, LL n){
    LL qs = n / 2, q = min(n - y + 1, min(n - x + 1, min(x, y))) - 1;
    if (x == qs + 1 && y == qs + 1)    return n * n;
    LL ans = 1ll * q * (8 * qs + 8 * (qs - q + 1)) / 2;
    if (n - x == q)    ans += n - q - y + 1;
    else if (y - 1 == q)    ans += n - 2 * q + 1 + n - q - 1 - x;
    else if (x - 1 == q)    ans += n - 2 * q + 1 + n - 2 * q - 2 + y - q - 1;
    else ans += n - 2 * q + 1 + n - 2 * q - 2 + n - 2 * q - 1 + x - q - 1;
    return ans;
}

解析:https://blog.csdn.net/weixin_42165981/article/details/100187841

posted @ 2019-09-02 14:06  shuai_hui  阅读(230)  评论(0编辑  收藏  举报