transform matrix 2D to 1D

前端 未结 3 426
温柔的废话
温柔的废话 2021-01-12 20:59

I have an issue passing a matrix 2D to a vector(1D array)with function in C. There is the code of what i want to create:

#include 
#define N          


        
3条回答
  •  心在旅途
    2021-01-12 21:32

    Iterate over the diagonals of the square, alternating direction each time.

    Here's a complete, working example (in c99).

    #include 
    
    #define max(a, b) ((a) > (b) ? (a) : (b))
    #define min(a, b) ((a) > (b) ? (b) : (a))
    
    void dezigzag(int out[64], int in[8][8]) {
        int n = 0;
        for (int diag = 0; diag < 15; diag++) {
            for (int i = max(0, diag - 7); i <= min(7, diag); i++) {
                out[n++] = diag % 2 ? in[diag - i][i] : in[i][diag - i];
            }
        }
    }
    
    int main(int argc, char *argv[]) {
        int out[64] = {-1};
        int in[8][8];
        for (int i = 0; i < 64; i++) {
            in[i % 8][i / 8] = i;
        }
        dezigzag(out, in);
        for (int i = 0; i < 64; i++) {
            printf("%d: %d\n", i, out[i]);
        }
        return 0;
    }
    

提交回复
热议问题