Switching rows and columns into a matrix with complexity O (1)

So, for homework, one of the things I was tasked with was replacing two rows or two columns with each other using a matrix that was built in an object of type class, using these 3 parameters to determine:

size_t _R;// Number of rows.
size_t _C;// Number of columns.
std::vector<T> mat;// array of T type variables to represent the matrix.

For example, if I had 3 rows and 3 columns, and an int vector array of 1,2,3,4,5,6,7,8,9, then replacing rows 0 and 1 would show that it looks 4,5 6.1.2.3.7.8.9.

So swap replacement is not a problem here, but I don’t understand what it is , how are you going to do this with O (1) complexity? What I wanted to do is individually switch between each type in a row / column, but then it will be O (n), right? Because it will depend on the number of elements in each row / column.

EDIT: Sample code for what I tried:

void swap_rows(const size_t& r1, const size_t& r2) {
    for (size_t i = 0; i < _C; i++)
    {
        T temp = mat[i + (r1 * _C)];
        mat[i + (r1 * _C)] = mat[i + (r2 * _C)];
        mat[i + (r2 * _C)] = temp;
    }
}

But I believe O (n) is complexity, so no-go: p

+4
source share
2 answers

One way to do this is to apply a modifier row and column to each of your dimensions, for example:

std::vector<size_t>(_R) row_i;
std::vector<size_t>(_C) col_i;

Then each of them is initialized, for example, {0, 1, 2}respectively. Then you access your elements by de-linking through these collections:

T getItem( size_t row, size_t column )
{
    return mat[ ( row_i[row] * _C ) + col_i[col] ) ];
}

T row, col, - .

, , :

std::swap( row_i[0], row_i[1] );

hey presto, 0 1 . , 3 x 3 1000 x 1000, - .

+2

- , O (_C) * O (2) = O (_C) 2 .

, O (1) , . , O (_R).

-2

All Articles