C ++中的对称矩阵

检查2D矩阵是否对称任务是在矩阵是对称的情况下输出YES,否则输出NO。

我没有得到预期的结果。有人可以帮帮我,请告诉我这段代码有什么问题

#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;
}

输入:第一行包含T - 测试用例数。 T测试案例如下。每个测试用例的第一行包含N - 大小的矩阵。接下来的N行包含长度为N的二进制字符串。

输出:为每个测试用例在新行中打印YES或NO

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.
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;
}