P2615 神奇的幻方
阿新 • • 發佈:2020-09-23
題目連結:https://www.luogu.com.cn/problem/P2615
題目解析:
說實話,剛看到時被嚇到了,感覺無從下手。然後才發現這是個大水題。直接模擬即可
先定義好n * n的陣列,然後依次填入數字,根據上一個填入數字的下標選擇當前這個數要填入的下標是多少。
1 #include <bits/stdc++.h> 2 using namespace std; 3 int arr[45][45]; 4 int main() { 5 int n; 6 cin >> n; 7 int t = 1; //t是每次要填的數 8int x = 1, y = n / 2 + 1; //第一個點要在第一行的中間 9 arr[x][y] = t; 10 int sum = n * n; 11 while (t <= sum) { 12 t++; //每次填了一個數後,t++ 13 if (x == 1 && y != n) { 14 x = n; 15 y = y + 1; 16 } else if (y == n && x != 1) { 17 y = 1; 18 x = x - 1; 19 } else if (x == 1 && y == n) { 20 x = x + 1; 21 } else if (x != 1 && y != n) { 22 if (arr[x - 1][y + 1] == 0) { 23 x = x - 1; 24 y = y + 1; 25 } else { 26 x = x + 1; 27 } 28 } 29 arr[x][y] = t; 30 } 31 for (int i = 1; i <= n; i++) { 32 for (int j = 1; j <= n; j++) { 33 cout << arr[i][j] << " "; 34 } 35 cout << endl; 36 } 37 return 0; 38 }