Traverse Matrix in Diagonal strips

前端 未结 16 1795
暖寄归人
暖寄归人 2020-11-28 02:55

I thought this problem had a trivial solution, couple of for loops and some fancy counters, but apparently it is rather more complicated.

So my question is, how woul

相关标签:
16条回答
  • 2020-11-28 03:49

    I thought this problem had a trivial solution, couple of for loops and some fancy counters

    Precisely.

    The important thing to notice is that if you give each item an index (i, j) then items on the same diagonal have the same value j+ni, where n is the width of your matrix. So if you iterate over the matrix in the usual way (i.e. nested loops over i and j) then you can keep track of the diagonals in an array that is addressed in the above mentioned way.

    0 讨论(0)
  • 2020-11-28 03:50

    I would probably do something like this (apologies in advance for any index errors, haven't debugged this):

    // Operation to be performed on each slice:
    void doSomething(const int lengthOfSlice,
                     elementType *slice,
                     const int stride) {
        for (int i=0; i<lengthOfSlice; ++i) {
            elementType element = slice[i*stride];
            // Operate on element ...
        }
    }
    
    void operateOnSlices(const int n, elementType *A) {
        // distance between consecutive elements of a slice in memory:
        const int stride = n - 1;
    
        // Operate on slices that begin with entries in the top row of the matrix
        for (int column = 0; column < n; ++column)
            doSomething(column + 1, &A[column], stride);
    
        // Operate on slices that begin with entries in the right column of the matrix
        for (int row = 1; row < n; ++row)
            doSomething(n - row, &A[n*row + (n-1)], stride);
    }
    
    0 讨论(0)
  • 2020-11-28 03:50

    A much easier implementation:

    //Assuming arr as ur array and numRows and numCols as what they say.
    int arr[numRows][numCols];
    for(int i=0;i<numCols;i++) {
        printf("Slice %d:",i);
        for(int j=0,k=i; j<numRows && k>=0; j++,k--)
        printf("%d\t",arr[j][k]);
    }
    
    0 讨论(0)
  • 2020-11-28 03:53

    Pseudo code:

    N = 2 // or whatever the size of the [square] matrix
    for x = 0 to N
      strip = []
      y = 0
      repeat
         strip.add(Matrix(x,y))
         x -= 1
         y -= 1
      until x < 0
      // here to print the strip or do some' with it
    
    // And yes, Oops, I had missed it... 
    // the 2nd half of the matrix...
    for y = 1 to N    // Yes, start at 1 not 0, since main diagonal is done.
       strip = []
       x = N
       repeat
          strip.add(Matrix(x,y))
          x -= 1
          y += 1
       until x < 0
      // here to print the strip or do some' with it
    

    (Assumes x indexes rows, y indexes columns, reverse these two if matrix is indexed the other way around)

    0 讨论(0)
提交回复
热议问题