题目说明:给定一个起点,剩下的用L形的三个方块进行填充。
题目解析:迭代。最大的正方形切成四个小正方形,一步步切下去直到最后剩余2*2的小正方形。在大正方形正中间四个方块,除起点所在象限的方块,即另外三个方块标记上相同数字。
Title Analysis English version: We can using iteration to solve problems. From the start position, starting to binary cut the matrix into four pieces until every sub-matrix is 2*2. I will mark the start position and the other three positions in the middle which has different quadrants besides the quadrant the start position in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
#include<iostream> #include<cmath> #include <memory.h> using namespace std; int matrix[512][512]; int mark = 0; void generator(int beginx, int beginy, int endx, int endy, int x2, int y2) { int order = endx - beginx + 1; int positions[4][2] = { {order / 2 - 1 + beginx, order / 2 - 1 + beginy}, {order / 2 - 1 + beginx, order / 2 + beginy}, {order / 2 + beginx, order / 2 + beginy}, {order / 2 + beginx, order / 2 - 1 + beginy} }; int min = abs(positions[0][0] - x2) + abs(positions[0][1] - y2), positionMin = 0; for (int i = 1; i < 4; i++) { int length = abs(positions[i][0] - x2) + abs(positions[i][1] - y2); positionMin = min < length ? positionMin : i; min = min < length ? min : length; } mark++; for (int i = 0; i < 4; i++) { if (i == positionMin) continue; else matrix[positions[i][0]][positions[i][1]] = mark; } if (order == 2) return; if (positionMin == 0)generator(beginx, beginy, positions[0][0], positions[0][1], x2 , y2); else generator(beginx, beginy, positions[0][0], positions[0][1], positions[0][0], positions[0][1]); if (positionMin == 1)generator(beginx, positions[1][1], positions[1][0], endy, x2, y2); else generator(beginx, positions[1][1], positions[1][0], endy, positions[1][0], positions[1][1]); if (positionMin == 2)generator(positions[2][0], positions[2][1], endx, endy, x2, y2); else generator(positions[2][0], positions[2][1], endx, endy, positions[2][0], positions[2][1]); if (positionMin == 3)generator(positions[3][0], beginy, endx, positions[3][1], x2, y2); else generator(positions[3][0], beginy, endx, positions[3][1], positions[3][0], positions[3][1]); } int main() { int n, x, y, n2; cin >> n; cin >> x; cin >> y; n2 = pow(2, n); matrix[x - 1][y - 1] = 0; generator(0, 0, n2 - 1, n2 - 1, x - 1, y - 1); for (int i = 0; i < n2; i++) { for (int j = 0; j < n2 - 1; j++) cout << matrix[i][j] << " "; cout << matrix[i][n2 - 1] << endl; } } |