这是今天在论坛看到的题目,自己也写了个一个很粗糙的解...
http://topic.csdn.net/u/20100731/11/410789b3-e638-4be1-8d18-7569ad79d44b.html?seed=1486254098&r=67426954#r_67426954
这一题,也被我拿来当公司应徵人的考题,不过好像也没人写出来....
输入数字n,编C++程序打印如图所示图形(c++):
#include "stdafx.h" #include <iostream> #include <vector> #include <iomanip> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int n = 1; cin>>n; int width = n + 2; vector<vector<int> > ary(width, vector<int>(width)); int final = width * width - 4; int direct_x = 1; int direct_y = 0; int x = 1; int y = 0; int depth = 0; for(int i = 1 ; i <= final ; i++) { ary[y][x] = i; x += direct_x; y += direct_y; if( x == (width - 1 - depth) && (direct_x == 1 && direct_y == 0)) { direct_x = 0; direct_y = 1; if(depth == 0) { x += direct_x; y += direct_y; } } else if( y == (width - 1 - depth) && (direct_x == 0 && direct_y == 1)) { direct_x = -1; direct_y = 0; if(depth == 0) { x += direct_x; y += direct_y; } } else if( x == (0 + depth) && (direct_x == -1 && direct_y == 0)) { direct_x = 0; direct_y = -1; if(depth == 0) { x += direct_x; y += direct_y; } } else if( y == (0 + depth) && (direct_x == 0 && direct_y == -1)) { direct_x = 1; direct_y = 0; x = 1 + depth; y = 1 + depth; depth++; } } for(int i = 0; i < width ; i++) { for(int j = 0 ; j < width; j++) { if(ary[i][j] > 0) cout<<setw(3)<<ary[i][j]; else cout<<setw(3)<<" "; } cout<<endl; } system("pause"); return 0; }