Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
2.7 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

void sort_vertical(int **matrix, int n, int m, int **result_matrix) {
    int *temp = (int *)malloc(n * m * sizeof(int));
    if (temp == NULL) {
        printf("n/a\n");
        return;
    }
    int k = 0;
    for (int j = 0; j < m; j++) {
        for (int i = 0; i < n; i++, k++) {
            temp[k] = matrix[i][j];
        }
        if (j % 2 == 1) {
            for (int start = k - n, end = k - 1; start < end; start++, end--) {
                int swap = temp[start];
                temp[start] = temp[end];
                temp[end] = swap;
            }
        }
    }
    k = 0;
    for (int j = 0; j < m; j++) {
        for (int i = 0; i < n; i++, k++) {
            result_matrix[i][j] = temp[k];
        }
    }
    free(temp);
}

void sort_horizontal(int **matrix, int n, int m, int **result_matrix) {
    int *temp = (int *)malloc(n * m * sizeof(int));
    if (temp == NULL) {
        printf("n/a\n");
        return;
    }
    int k = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++, k++) {
            temp[k] = matrix[i][j];
        }
        if (i % 2 != 0) {
            for (int start = k - m, end = k - 1; start < end; start++, end--) {
                int swap = temp[start];
                temp[start] = temp[end];
                temp[end] = swap;
            }
        }
    }
    k = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++, k++) {
            result_matrix[i][j] = temp[k];
        }
    }
    free(temp);
}

void input(int ***matrix, int *n, int *m) {
    scanf("%d %d", n, m);
    *matrix = (int **)malloc(*n * sizeof(int *));
    for (int i = 0; i < *n; i++) {
        (*matrix)[i] = (int *)malloc(*m * sizeof(int));
        for (int j = 0; j < *m; j++) {
            scanf("%d", &(*matrix)[i][j]);
        }
    }
}

void output(int **matrix, int n, int m) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            printf("%d", matrix[i][j]);
            if (j < m - 1) printf(" ");
        }
        printf("\n");
    }
    printf("\n");
}

int main() {
    int **matrix, **result;
    int n, m;

    input(&matrix, &n, &m);
    result = (int **)malloc(n * sizeof(int *));
    for (int i = 0; i < n; i++) {
        result[i] = (int *)malloc(m * sizeof(int));
    }

    sort_vertical(matrix, n, m, result);
    output(result, n, m);

    sort_horizontal(matrix, n, m, result);
    output(result, n, m);

    // Освобождение памяти
    for (int i = 0; i < n; i++) {
        free(matrix[i]);
        free(result[i]);
    }
    free(matrix);
    free(result);

    return 0;
}
Leave a Comment