# C ++中的对称矩阵

##### 问题描述投票：0回答：1

``````#include<iostream>
#include<vector>
using namespace std;
bool rev(int n)
{
int n1,d,rn=0;
n1=n;
while(n>0)
{
d=n%10;
rn=(rn*10)+d;
n/=10;
}
if(n1==rn)
{return true;}
else
return false;
}
bool XAxisSymCheck(vector<int> vect)
{
// Declaring iterator to a vector
vector<int>::iterator ptr;
for (ptr = vect.begin(); ptr < vect.end(); ptr++)
{ if(!rev(*ptr)) // reversing the elements in each element of vector to check whether its symmetric or not .. similar to palindrome
{
return false;
}
}
}
int main()
{int testcase;
cin>>testcase;
for(int k=0;k<testcase;++k)
{vector<int> rows;
bool IsSymmetric=true;
int row;
cin >> row;
// read each row and append to the "rows" vector
for (int r = 0; r < row; r++)
{
int line;
cin >> line;
rows.push_back(line);
}
if(XAxisSymCheck(rows))
{int i,j;
i=0;
j=row-1;
while(i<j) // looping through the elements of vector and checking the first element with last element , second element with the second last element and so on.
{
if(rows[i]!=rows[j])
{
IsSymmetric=false;
break;
}
i++;
j--;
}
}
else
{
IsSymmetric=false;
}
cout << (IsSymmetric ? "Yes" : "No") << endl;
}
return 0;
}
``````

``````SAMPLE INPUT
5
2
11
11
4
0101
0110
0110
0101
4
1001
0000
0000
1001
5
01110
01010
10001
01010
01110
5
00100
01010
10001
01010
01110

SAMPLE OUTPUT
YES
NO
YES
YES
NO

Test Case #1: Symmetric about both axes, so YES.

Test Case #2: Symmetric about X-axis but not symmetric about Y-axis, so NO.

Test Case #3: Symmetric about both axes, so YES.

Test Case #4 and #5 are explained in statement.
``````
c++ algorithm vector data-structures
##### 1个回答
1

1）你永远不会从`true`返回`XAxisSymCheck`（通过检查编译器警告很容易发现，例如`g++ -Wall matrix.cpp`

``````bool XAxisSymCheck(vector<int> vect) {
vector<int>::iterator ptr;
for (ptr = vect.begin(); ptr < vect.end(); ptr++) {
if(!rev(*ptr, vect.size()))
return false;

}
return true;
}
``````

2）当你的`XAxisSymCheck`失败时，你没有将`IsSymmetric`设置为`false`（至少在编辑前的原始帖子中）

``````for(int k=0;k<testcase;++k) {
vector<int> rows;
bool IsSymmetric = true;

// ....

if (XAsxisSymCheck(rows)) {
// ...
} else {
IsSymmetric = false;
}

cout << (IsSymmetric ? "Yes" : "No") << endl;
}
``````

3）如果一条线具有前导零，则反向检查失败，因为反向经常不足以乘以10。

``````bool rev(int n,int len) {
int n1,d,rn=0;
n1=n;
for (int i = 0; i < len; i++)
{
d=n%10;
rn=(rn*10)+d;
n/=10;
}
return n1==rn;
}
``````