总而言之就是输出形如下图的数组:

蛇形数组

笔试过程中想的是找规律填充,结果太复杂了,没能解决;

结束后改用直接的方法,倒是一刻钟搞定,唉;

c++代码如下:

#include<iostream>
#include <vector>
#include<functional>

int main()
{
    using namespace std;
    int N = 0;
    cin >> N;
    cout << endl << endl;
    int n = N - 1;
    vector<vector<int>> mat(N, vector<int>(N, 0));
    
    auto op1 = [](int& i, int& j){j++;}; //→
    auto op2 = [](int& i, int& j){i++;}; //↓
    auto op3 = [](int& i, int& j){j--;}; //←
    auto op4 = [](int& i, int& j){i--;}; //↑
    function<void (int&, int&)> op = op1;
    int cur = 0;
    int i = 0, j = 0;
    int st = 0;
    while (cur++ != N * N)
    {
        mat[i][j] = cur;
        op(i, j);
        if (i == st && j == n) op = op2;
        if (i == n && j == n) op = op3;
        if (i == n && j == st) op = op4;
        if (i == st && j == st) {op = op1; st++; n--; i = st; j = st;}
    }
    for (auto& l : mat) {
        for (auto i : l) cout << i << "\t";
        cout << endl;
    } 
}

 


avatar
65535
3 Comment threads
3 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Cıvata一树小草shy泠石樱灯笼 Recent comment authors
trackback
shy泠
Guest

#include #include using namespace std; void cons(vector<vector > &matrix, int x, int y, in… 展开

石樱灯笼
Guest

写了个php版的,用了好长时间,估计我去面试我也答不上 <?php $snakeArray1 = snakeArray1(5, 5); printXYarray($snakeArray1); f… 展开

石樱灯笼
Guest

也行。域名邮箱我还没搞新的。评论回复我也没搞。