// More of a math problem #include #define MAX 100 // *** THERE IS AN SIMPLER SOLUTION, THIS ONE IS BLOATED AND BAD *** // // There are two main movements: // 1: diagonal move, which includes two ways: i++&&j-- and i--&&j++ // ^way = 0 ^way = 1 // and for the diagonal move, the are six scenarios where the next step hits the // boundary. // a: nexti < n, nextj < 0 where i is valid. Results in i++ // b: nexti < 0, nextj < n where j is valid. Results in j++ // c: nexti >=n, nextj < 0 where none is valid. Results in j++ // d: nexti <0, nextj >= n where none is valid. Results in i++ // e: nexti >=n, nextj >=0 where j is valid. Results in j++ // f: nexti >=0, nextj >=n where i is valid. Results in i++ // // 2: horizontal and vertical move, which includes two ways as well: i++ and j++ // The movement stops when i == j and j == n void fill(int matrix[][MAX], int n); int main(void) { int n; scanf("%d", &n); int matrix[n][MAX]; fill(matrix, n); for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { printf("%d ", matrix[i][j]); } printf("%d\n", matrix[i][n - 1]); } return 0; } void fill(int matrix[][MAX], int n) { int i = 0, j = 0; int nexti, nextj; int way = 1; int count = 1; while (count <= n * n) { matrix[i][j] = count++; if (way == 1) { nexti = i + 1; nextj = j - 1; } else { nexti = i - 1; nextj = j + 1; } // Validate if the next step is in the matrix. // First: the next step is within matrix. if (nexti >= 0 && nexti < n && nextj >= 0 && nextj < n) { i = nexti; j = nextj; } else { // Second: the next step is out of boundary. if (nextj < 0 && nexti < n) { i++; } else if (nexti < 0 && nextj < n) { j++; } else if (nexti >= n && nextj < 0) { j++; } else if (nexti < 0 && nextj >= n) { i++; } else if (nexti >= n && nextj >= 0) { j++; } else if (nexti >= 0 && nextj >= n) { i++; } way *= -1; } } }