Spiral Matrix II

    xiaoxiao2021-03-26  22

    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example, Given n = 3,

    You should return the following matrix:

    [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]

    vector<vector<int> > fun(int n) { vector<vector<int> > result(n, vector<int>(n)); int left = 0; int right = n-1; int top = 0; int bottom = n-1; int count = 0; int total = n*n; while (count < total) { for (int i = left; i <= right && count < total; i++) { count++; result[top][i] = count; } top++; for (int i = top; i <= bottom && count < total; i++) { count++; result[i][right] = count; } right--; for (int i = right; i >= left && count < total; i--) { count++; result[bottom][i] = count; } bottom--; for (int i = bottom; i >= top && count < total; i--) { count++; result[i][left] = count; } left++; } return result; }

    转载请注明原文地址: https://ju.6miu.com/read-660691.html

    最新回复(0)