我在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)时,程序终止于Segmentation故障。奇怪的是,当与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
,如上所述。我做错了什么?