【发布时间】:2018-08-21 15:55:30
【问题描述】:
我正在开发一个程序,它接收一个 5x5 的字符数组并找到最长的相同字符列表,连接的意思是上、下、左或右相邻(意味着没有对角线)。然而,输出偏离 1,给出 6 而不是正确的 7,输入:
a b c c b
a c b c c
c a a b a
b b a a c
a a a b a
谁能帮我找出我的代码中的错误是什么? (我的代码在下面)
详细信息: 缺少的字符位于索引 [3][3] 处(索引从 0 开始)。当我测试我的look() 函数时,它工作正常,当我将它传递给 row 3 和 col 传递 2 时,它会将 [3][3] 添加到要返回的最终向量中,但我认为有些东西没有平移使用递归。
我已经对此进行了调试,但没有成功,您可以在我的代码中看到调试打印。
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <utility>
using namespace std;
char grid[5][5];
bool seen[5][5];
int cnt = 1;
int maxn = 0;
vector<pair<int, int>> look(int row, int col)
{
//
vector<pair<int, int >> node_list;
if (row != 0)
if (grid[row - 1][col] == grid[row][col])
if (!seen[row - 1][col])
node_list.push_back(make_pair(row - 1, col));
if (row != 4)
if (grid[row + 1][col] == grid[row][col])
if (!seen[row+1][col])
node_list.push_back(make_pair(row + 1, col));
if (col != 0)
if (grid[row][col - 1] == grid[row][col])
if (!seen[row][col-1])
node_list.push_back(make_pair(row, col - 1));
if (col != 4)
if (grid[row][col + 1] == grid[row][col])
if (!seen[row][col+1])
node_list.push_back(make_pair(row, col + 1));
if (binary_search(node_list.begin(), node_list.end(), make_pair(2, 2)))
cout << "HAPPENED^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << "\n";
return node_list;
}
void search(int row, int col)
{
for (pair<int, int> a : look(row, col))
{
if (!seen[a.first][a.second])
{
seen[a.first][a.second] = true;
cnt++;
cout << "COUNTED and now SEARCHING " << a.first << " " << a.second << "\n";
cout << "search about to be called on " << a.first << " " << a.second << "\n";
search(a.first, a.second);
}
}
if (cnt > maxn)
maxn = cnt;
cout << "CNT: " << cnt << "\n";
cnt = 1;
return;
}
int main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
cin >> grid[i][j];
seen[i][j] = false;
}
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (!seen[i][j])
{
cout << "INITIALLY SEARCHING: " << i << " " << j << "\n";
seen[i][j] = true;
cout << "search about to be called on " << i << " " << j << "\n";
search(i, j);
}
else
cout << "NO INITIAL SEARCH, SEEN: " << i << " " << j << "\n";
}
}
cout << maxn << "\n";
return 0;
}
【问题讨论】:
-
我通过 [3][2] 的输出应该是什么?
-
那不是实际输入,是我通过look()函数的测试输入,其中3为行,2为列。它输出 2 2、4 2 和 3 3。
-
您是否尝试过附加调试器以便逐步完成程序?这应该可以让你找到它做一些你没想到的事情的地方。
标签: c++ c++11 recursion graph connected-components