top1编程
← 返回题目
题解

【基础】螺旋矩阵

1 条题解

  • 0
    @ 2026-7-29 0:18:49
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int n, x, y;
        cin >> n >> x >> y;
            
        int up = x, down = n - x + 1, left = y, right = n - y + 1;
        
        //确定矩阵中第x行第y列的数,在矩阵的第t层
        int t = min(min(up, down), min(left, right)); 
    
        int ans = 1, r = 1, c = 1;
        for(int i = 1; i < t; i ++)
        {
            ans += 4 * n - 4; //第t层左上角的第一个数为ans
            r ++, c ++; //第t层左上角的位置为(r,c)
            n -= 2;//第t层的子矩阵大小减少2
        }
        
        if(x == r) ans += y - c; //如果在该层的第一行上
        //如果在该层的最后一列
        else if(y == c + n -1) ans += n - 1 + x - r;
        //如果在该层的最后一行
        else if(x == r + n - 1 ) ans += 3 * n - 3 - (y - c);
        //如果在该层的第一列
        else ans += 4 * n - 4 - (x - r);
        
        cout << ans << endl;
        
        return 0;
    }
    
    • 1