Title Link
Title Analysis
Simple simulation questions
Solving problems
1. Traverse 1-sqrt(N) to get the closest m, n (M > n)
2. Clockwise rotation:
Looking for the law, every time we reach the border, we actually turn to be certain,
Record the current running direction and change the direction at the boundary
Attention points
At the beginning of initialization of two-dimensional array, I want to save some time. Write it as fill(vis[0], vis[0]+(N+1)*(n+1), false)
In fact, it does not strictly assign values to the small matrices to be used, and it will go down line by line, so there is an error;
AC program (C + +)
/********************************** *@ID: 3stone *@ACM: PAT.A1105 Spiral Matrix *@Time: 18/9/20 *@IDE: VScode 2018 + clang++ ***********************************/ #include<cstdio> #include<cstring> #include<queue> #include<algorithm> #include<cmath> using namespace std; const int maxn = 1010; int N; int matrix[maxn][maxn]; bool vis[maxn][maxn]; //Is the tag filled with numbers priority_queue<int> Q; //Store data for heap sorting void find_matrix(int& n, int& m) { int sqt = (int)sqrt((1.0) * N); for(int i = sqt; i>= 1; i--) { if(N % i == 0) { n = i; break; } } m = N / n; } //Determine whether the direction needs to be changed void judgeDirection(int& i, int& j, int& direction, int n, int m) { switch(direction) { case 1: j--;//go left if(j < 0 || vis[i][j] == true) { //frontier or used j++; //recover i--; direction = 3; //true on } break; case 2: j++;//go right if(j >= n || vis[i][j] == true) { j--; i++; direction = 4; //turn down } break; case 3: i--; //go up if (i < 0 || vis[i][j] == true) { i++; j++; direction = 2; //turn right } break; case 4: i++; // go down if(i >= m || vis[i][j] == true) { i--; j--; direction = 1; //true on } break; //default: }//switch } int main() { int n, m, temp; while(scanf("%d", &N) != EOF) { for(int i = 0; i < N; i++) { scanf("%d", &temp); Q.push(temp); } //fill(vis[0], vis[0] + maxn * maxn, false); / / Yes, the array is not large for(int i = 0; i < m; i++) fill(vis[i], vis[i] + n, false); //find m and n find_matrix(n, m); //how to intial the matrix clockwisely int direction = 2; //go right at first int i = 0, j = 0; while(!Q.empty()) { matrix[i][j] = Q.top(); Q.pop(); vis[i][j] = true; //Directions 1, 2, 3 and 4 represent left, right, up and down respectively judgeDirection(i, j, direction, n, m); }//while //output the matrix for(int i = 0; i < m; i++) { for(int j = 0; j < n - 1; j++) { printf("%d ", matrix[i][j]); } printf("%d\n", matrix[i][n - 1]); } }//while-scanf return 0; }