【发布时间】:2016-04-03 23:52:06
【问题描述】:
我在这里看到了几个不能完全回答我的问题的问题。我正在尝试对面试问题中经常使用的经典矩阵旋转问题进行演绎。我对 M x N 矩阵感兴趣,而不是关注方阵。
对于输入矩阵
1 2 3
4 5 6
7 8 9
1 2 3
我想把矩阵转换成
3 2 1
9 8 7
6 5 4
3 2 1
这是我写的代码:
#include <iostream>
#include <vector>
#include <algorithm>
void do_swaps(int& a, int& b, int& c, int& d) {
std::swap(a, b);
std::swap(c, d);
}
void rotate(std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for(size_t i = 0; i < m/2; ++i) {
for(size_t j = 0; j <= n/2; ++j) {
do_swaps(v[i][j], v[m-i-1][n-j-1], v[m-j-1][i], v[j][n-i-1]);
}
}
}
void print(const std::vector<std::vector<int>>& v) {
size_t m = v.size();
size_t n = v[0].size();
for(size_t i = 0; i < m; ++i) {
for(size_t j = 0; j < n; ++j) {
std::cout << v[i][j] << ' ';
}
std::cout << '\n';
}
}
int main() {
std::vector<std::vector<int>> m{{1,2,3}, {4,5,6}, {7,8,9}, {1, 2, 3}};
std::cout << "Before: \n";
print(m);
rotate(m);
std::cout << "\nAfter: \n";
print(m);
}
这是我的输出:
Before:
1 2 3
4 5 6
7 8 9
1 2 3
After:
3 2 1
9 5 7
6 8 4
3 2 1
我的代码适用于 3 x 3 矩阵(尚未测试更高维矩阵),但我的代码中似乎有一个错误,导致最里面的元素保持未交换。
在for(size_t j = 0; j <= n/2; ++j) { 行中,我尝试将停止条件调整为包括j < (n+1)/2; 和j < (n-1)/2; 在内的几项内容,但它保持不变。
谁能解释我的算法哪里出了问题?
【问题讨论】:
标签: c++ algorithm matrix rotation