如何打印BFS路径本身而不是此字梯的路径长度?

时间:2019-12-18 05:33:49

标签: c++ vector queue breadth-first-search

我收到了实现广度优先搜索的单词阶梯的入门代码/算法。该程序采用单词词典,但我对其进行了修改以采用输入文件。我得到的算法将打印从源单词到目标单词的路径长度,例如:如果需要4次转换才能到达目标单词,它将打印4。我想打印路径本身。例如:如果源词是“ TOON”,源词是“ PLEA”,则应打印“ TOON-> POON-> POIN-> PLIN-> PLIA-> PLEA”

到目前为止,我尝试添加一个循环,该循环将队列中的单词附加到向量上,然后返回向量,但是我遇到了一个我不理解的错误。

main.cpp:42:18: error: no matching member function for
    call to 'push_back'
transformation.push_back(Q.front());

我为此感到难过了几天,所以我们将不胜感激。我是C ++的新手,所以请原谅我的任何错误。

这是代码

#include<bits/stdc++.h>
#include <iostream>

using namespace std;

// To check if strings differ by exactly one character 
bool nextWord(string & a, string & b) {
  int count = 0; // counts how many differeces there
  int n = a.length();

  // Iterator that loops through all characters and returns false if there is more than one different letter 
  for (int i = 0; i < n; i++) {
    if (a[i] != b[i]) {
      count++;
    }

    if (count > 1) {
      return false;
    }
  }
  return count == 1 ? true : false;
}

// A queue item to store the words
struct QItem {
  string word;
};

// Returns length of shortest chain to reach 'target' from 'start' 
// using minimum number of adjacent moves. D is dictionary 
int wordLadder(string & start, string & target, set < string > & D) {
  vector < string > transformation;

  // Create a queue for BFS and insert 'start' as source vertex 
  queue < QItem > Q;
  QItem item = {
    start
  }; // Chain length for start word is 1 
  Q.push(item);
  transformation.push_back(Q.front());

  // While queue is not empty 
  while (!Q.empty()) {

    // Take the front word 
    QItem curr = Q.front();
    Q.pop();

    // Go through all words of dictionary 
    for (set < string > ::iterator it = D.begin(); it != D.end(); it++) {
      // Proccess the next word according to BFS
      string temp = * it;
      if (nextWord(curr.word, temp)) {
        // Add this word to queue from the dictionary
        item.word = temp;
        Q.push(item);

        // Pop from dictionary so that this word is not repeated
        D.erase(temp);

        // If we reached target 
        if (temp == target) {
          return 0;
        }
      }
    }
  }

  return 0;
}

string start;
string target;

// Driver program 
int main() {
  // make dictionary 
  std::ifstream file("english-words.txt");
  set < string > D;

  copy(istream_iterator < string > (file),
    istream_iterator < string > (),
    inserter(D, D.end()));

  cout << endl;
  cout << "Enter Start Word" << endl;
  cin >> start;
  cout << "Enter Target Word" << endl;
  cin >> target;

  cout << wordLadder(start, target, D);
  return 0;
}

1 个答案:

答案 0 :(得分:3)

您正在尝试将错误的对象附加到vector<string>

更改

transformation.push_back(Q.front());

transformation.push_back(Q.front().word);