生成1-N*N的矩阵,一圈一圈的

来源:互联网 发布:大专程序员 编辑:程序博客网 时间:2024/05/20 20:56
#include <iostream>using namespace std;int N;int data[100][100];bool visit[100][100];void getNext(int status, int& nx, int &ny){switch (status){case 0://rightnx = 0, ny = 1; break;case 1://downnx = 1, ny = 0; break;case 2://leftnx = 0, ny = -1; break;case 3://upnx = -1, ny = 0; break;}}bool isVaild(int x, int y){if(visit[x][y])return false;if( x < 0 || x > N -1 || y < 0 || y > N - 1)return false;return true;}int main(){cin >> N;for (int i = 0; i < N; i++){for (int j = 0; j < N; j++){data[i][j] = 0;visit[i][j] = false;}}int status = 0;int cx = 0, cy =-1;int nx,ny;for(int num = 1; num <= N * N; ){getNext(status, nx, ny);cx += nx;cy += ny;if (isVaild(cx, cy)){data[cx][cy] = num;visit[cx][cy] = true;num++;}else{status = (status + 1) % 4;cx -= nx;cy -= ny;}}for (int i = 0; i < N; i++){for (int j = 0; j < N; j++){cout << data[i][j] << " ";}cout << endl;}/*for (int i = 0; i < N; i++){for (int j = 0; j < N; j++){cout << visit[i][j] << " ";}cout << endl;}*/}

0 0