Created
August 13, 2013 08:56
-
-
Save chengluyu/6219214 to your computer and use it in GitHub Desktop.
蛇形矩阵
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main(int argc, char const *argv[]) | |
{ | |
const int MAX = 102; | |
const int STEP[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; | |
int matrix[MAX][MAX] = {0}; | |
int n, x, y, s = 0, sum = 0; | |
cin >> n; | |
x = y = n; | |
for (int i = 0; i < MAX; ++i) { | |
matrix[0][i] = matrix[n + 1][i] = matrix[i][0] = matrix[i][n + 1] = 1; | |
} | |
for (int i = n * n; i > 0; --i) { | |
matrix[x][y] = i; | |
if (matrix[x + STEP[s][0]][y + STEP[s][1]] && ++s == 4) | |
s = 0; | |
x += STEP[s][0]; | |
y += STEP[s][1]; | |
} | |
for (int i = 1; i <= n; ++i) { | |
for (int j = 1; j <= n; ++j) { | |
cout << matrix[i][j] << ' '; | |
if (i == j || i + j == n + 1) | |
sum += matrix[i][j]; | |
} | |
cout << endl; | |
} | |
cout << sum; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment