有谁知道对矩阵进行右循环移位的有效方法?顺便说一句,矩阵是二进制的,但求解非二进制矩阵的方法也可以。
现在,我正在考虑为矩阵的行实现一个循环数组,并在需要移位操作时更新每一行。
我正在考虑的另一种方法是实现一个指向由 vector 表示的(矩阵的)列的指针 vector ,并在发生移位操作时交换它们。
例如
1 2 3
4 5 6
7 8 9
右移
3 1 2
6 4 5
9 7 8
如果我还需要将矩阵向下移动,那么所有这些解决方案都会出现另一个问题。有效地实现这两个操作,完全超出了我的范围。
降档
9 7 8
3 1 2
6 4 5
最佳答案
也许是这样的,
class matrix {
std::vector<bool> elements;
int rows, cols, row_ofs, col_ofs;
std::size_t index(int r, int c) {
r = (r + row_ofs) % rows;
c = (c + col_ofs) % cols;
return std::size_t(r)*cols + c; // row major layout
}
public:
matrix() : rows(0), cols(0) {}
matrix(int r, int c)
: elements(std::size_t(r)*c), rows(r), cols(c) {}
int num_rows() const { return rows; }
int num_cols() const { return cols; }
std::vector<bool>::reference operator()(int r, int c) {
return elements.at(index(r,c));
}
bool operator()(int r, int c) const {
return elements.at(index(r,c));
}
void rotate_left() { col_ofs = (col_ofs+1 ) % cols; }
void rotate_right() { col_ofs = (col_ofs+cols-1) % cols; }
void rotate_up() { row_ofs = (row_ofs+1 ) % rows; }
void rotate_down() { row_ofs = (row_ofs+rows-1) % rows; }
};
(未经测试)
编辑:这是一个替代方案:在内部使用 std::deque
关于c++ - 矩阵循环移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1478734/