Advertisement
yarin0600

Untitled

Nov 27th, 2023
739
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. bool solution(std::vector<std::string> inputArray)
  2. {
  3.    const size_t inputArraySize = inputArray.size();
  4.    const size_t size = inputArray[0].size();
  5.    int v{};
  6.    for (int i{1}; i < inputArraySize; ++i)
  7.    {
  8.       if (inputArray[i].size() != size)
  9.       {
  10.          return false;
  11.       }
  12.    }
  13.    bool solved = false;
  14.    for (; v < inputArraySize && !solved; ++v)
  15.    {
  16.       solved = false;
  17.       std::vector<bool> visited(inputArraySize, false);
  18.       backtracking(inputArray, v, visited, solved);
  19.    }
  20.    return solved;
  21. }
  22.  
  23. void backtracking(std::vector<std::string> &inputArray, int currentVertex, std::vector<bool> &visited, bool &solved)
  24. {
  25.    const size_t inputArraySize = inputArray.size();
  26.    if (1 == std::count(visited.begin(), visited.end(), false))
  27.    {
  28.       solved = true;
  29.    }
  30.    // current vertex can go to ANY STRING that is not visited YET!
  31.    else if (!visited[currentVertex] && !solved)
  32.    {
  33.       visited[currentVertex] = true;
  34.       // trying to find who is a neighbor on our abstract graph - Any inputArray[curNeighbor] who has mismatches = 1 with inputArray[currentVertex] string
  35.       // important thing - we can pick only one, if we go backtrack then we do not! choose that curNeighbor but we choose different one
  36.       for (int currentNeighbor{}; currentNeighbor < inputArraySize; ++currentNeighbor)
  37.       {
  38.          // if I visited already this neighbor in current path or it's me... then skip this iteration
  39.          if (currentNeighbor == currentVertex || visited[currentNeighbor])
  40.             continue;
  41.          // now try to find if the current contender has mismatch = 1 with currentVertex
  42.          int misMatches = 0;
  43.          const size_t sizeOfCurrentString = inputArray[currentVertex].size();
  44.          for (int idx{}; idx < sizeOfCurrentString && misMatches <= 1; ++idx)
  45.          {
  46.             if (inputArray[currentVertex][idx] != inputArray[currentNeighbor][idx])
  47.                ++misMatches;
  48.          }
  49.          // might be a good for solution
  50.          if (misMatches == 1)
  51.          {
  52.             backtracking(inputArray, currentNeighbor, visited, solved);
  53.             visited[currentNeighbor] = false; // backtrack!!!
  54.          }
  55.       }
  56.    }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement