easy
2025-06-28 15:58:16
发布于:浙江
0阅读
0回复
0点赞
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> generateMatrix(int n) {
    vector<vector<int>> matrix(n, vector<int>(n, 0));
    
    vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    int row = 0, col = 0, dir_idx = 0;
    int num = 1;
    while (num <= n * n) {
        matrix[row][col] = num;
        num++;
        
        int next_row = row + directions[dir_idx].first;
        int next_col = col + directions[dir_idx].second;
        
        if (next_row < 0 || next_row >= n || 
            next_col < 0 || next_col >= n || 
            matrix[next_row][next_col] != 0) {
            dir_idx = (dir_idx + 1) % 4;
            next_row = row + directions[dir_idx].first;
            next_col = col + directions[dir_idx].second;
        }
        
        row = next_row;
        col = next_col;
    }
    return matrix;
}
int main() {
    int n,i,j;
    cin>>n>>i>>j;
    vector<vector<int>> result = generateMatrix(n);
    cout<<result[i-1][j-1];
    return 0;
}
这里空空如也







有帮助,赞一个