Swap rows or columns of a 2d array in O(1) time in c++

蹲街弑〆低调 提交于 2019-12-12 04:53:00

问题


My question is that how can you swap two rows or two columns of a 2D array in O(1) time?,I searched on internet and i found a function memcpy but i don't know how to use it. for example

given a matrix:

1 2 3 
4 5 6 
7 8 9

if we swap row 1 and row 2

4 5 6
1 2 3
7 8 9

回答1:


You can use an indirect array on both rows and columns. In other words to access an element i,j you use

data[rowix[i]][colix[j]]

instead of plain

data[i][j]

This is still an O(1) for element access (albeit with a larger constant factor), but also allows you to swap both rows and columns in constant time (just swap the index arrays elements).

In C++

template<int ROWS, int COLS, typename T>
struct Mat2d {
    T data[ROWS][COLS];
    int colix[COLS], rowix[ROWS];
    Mat2d() {
        for (int i=0; i<ROWS; i++) {
            for (int j=0; j<COLS; j++) {
                data[i][j] = T();
            }
        }
        for (int i=0; i<ROWS; i++) rowix[i] = i;
        for (int j=0; j<COLS; j++) colix[j] = j;
    }
    T& operator()(int i, int j) { return data[rowix[i]][colix[j]]; }
    T operator()(int i, int j) const { return data[rowix[i]][colix[j]]; }
    void swapRows(int i1, int i2) { std::swap(rowix[i1], rowix[i2]); }
    void swapCols(int j1, int j2) { std::swap(colix[j1], colix[j2]); }
};

Every problem in programming can be solved by adding an indirection level (except the problem of having too many indirection levels) ;-)



来源:https://stackoverflow.com/questions/26696705/swap-rows-or-columns-of-a-2d-array-in-o1-time-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!