递归和非递归打印螺旋矩阵

#include <iostream> #include <cstdlib> #include <cstring> int **matrix; int value = 1; void recursion (int row, int col, int len) // row, col代表本次左上角元素的位置, len为本次矩阵边长 { if (len <= 0) { return; } int i = row, j = col; while (j < col + len) { matrix[i][j++] = value++; } j--; i++; while (i < row + len) { matrix[i++][j] = value++; } i--; j--; while (j >= col) { matrix[i][j--] = value++; } j++; i--; while (i > row) { matrix[i--][j] = value++; } i++; j++; recursion(i, j, len - 2); } void no_recursion ( int n ) // n为整个矩阵的边长 { int i, j, len, col, row; for (i = 0, j = 0, len = n; len > 0; ) { row = i; col = j; while (j < col + len) { matrix[i][j++] = value++; } j--; i++; while (i < row + len) { matrix[i++][j] = value++; } i--; j--; while (j >= col) { matrix[i][j--] = value++; } j++; i--; while (i > row) { matrix[i--][j] = value++; } i++; j++; len = len - 2; } } int main() { int N = 7, i, j; matrix = (int**) malloc(sizeof(int*) * N); for (i = 0; i < N; i++) { matrix[i] = (int*) malloc(sizeof(int) * N); memset(matrix[i], 0, sizeof(int) * N); } no_recursion(N); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { std::cout << matrix[i][j] << ' '; } std::cout << std::endl; } for (i = 0; i < N; i++) { free(matrix[i]); } free(matrix); return 0; }

你可能感兴趣的:(include,Matrix,recursion)