【发布时间】:2018-05-11 02:52:52
【问题描述】:
我正在用 C++ 解决编程problem,它需要检查所有 9! 3 X 3 矩阵的排列
1 2 3
4 5 6
7 8 9
我认为,我已经编写了正确的逻辑,并且实际上在 2 X 2 矩阵上对其进行了测试(当然,通过从 3 X 3 调整 2 X 2 的代码。),结果打印出正确的输出。但是当我为实际约束运行程序时(即 3 X 3 matirx),程序以分段错误终止。奇怪的是,当用 GDB 调试时,它会打印出来
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff74f6bbc in _int_malloc (av=av@entry=0x7ffff7839b20 <main_arena>,
bytes=bytes@entry=12) at malloc.c:3353
3353 malloc.c: No such file or directory.
这是我写的 C++ 代码:
#include <bits/stdc++.h>
using namespace std;
int min_count;
map<string, bool> mp;
vector<vector<int>>vec(3, vector<int>(3, 0));
// n <= 17
bool isPrime(int n) {
return n == 2 or n == 3 or n == 5 or n == 7 or n == 11 or n == 13 or n == 17;
}
// get a String representation of the matrix vec
string getStringRepresentation(vector<vector<int>> vec) {
string str = "";
for(auto i : vec) {
for(auto j : i)
str += ('0' + j);
}
return str;
}
void printRecursive(vector<vector<int>> &vec, map<string, bool> &mp, int count) {
string str = getStringRepresentation(vec);
if(str == "123456789" and count <= min_count)
min_count = count;
//cout << str << " " << count << endl;
if(mp[str])
return;
mp[str] = true;
for(int i = 0; i < vec.size(); ++i) {
for(int j = 0; j < vec[i].size(); ++j) {
if(j != vec[i].size() - 1 and isPrime(vec[i][j] + vec[i][j+1])) {
swap(vec[i][j], vec[i][j+1]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i][j+1]);
}
if(i != vec.size() - 1 and isPrime(vec[i][j] + vec[i+1][j])) {
swap(vec[i][j], vec[i+1][j]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i+1][j]);
}
}
}
}
// solve for each test case
void solve() {
for(auto &i : vec) {
for(auto &j : i) {
cin >> j;
}
}
//cout << getStringRepresentation(vec) << endl;
min_count = INT_MAX;
printRecursive(vec, mp, 0); // recursively examine all possible states.
// if min_count is not changed(i.e. reamains equal to INT_MAX then the required state is unreachable, print -1 to indicate)
cout << (min_count == INT_MAX ? -1 : min_count) << endl;
}
int main() {
int test; // test are the number of test cases, each will invoke the solve() function.
cin >> test;
while(test--)
solve();
}
对于输入
1
7 3 2
4 1 5
6 8 9
程序本应输出6,但结果为SIGSEGV,如前所述。我做错了什么?
【问题讨论】:
-
请不要在此处发布的代码中使用`
`。这不是标准的。尝试修剪程序。目标是minimal reproducible example。 -
请不要发布需要潜在助手通过
cin输入值的程序。使程序独立。 -
编译打开所有警告,并修复代码以删除它们。
-
趣味拼图。这个程序会在无限循环中继续交换 7 和 4 吗?
-
问题很好,反对者无视。但是您应该尝试自己调试它。例如。当你看到段错误等时在 GDB 中做一个堆栈跟踪
标签: c++ malloc segmentation-fault