Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool solution(std::vector<std::string> inputArray)
- {
- const size_t inputArraySize = inputArray.size();
- const size_t size = inputArray[0].size();
- int v{};
- for (int i{1}; i < inputArraySize; ++i)
- {
- if (inputArray[i].size() != size)
- {
- return false;
- }
- }
- bool solved = false;
- for (; v < inputArraySize && !solved; ++v)
- {
- solved = false;
- std::vector<bool> visited(inputArraySize, false);
- backtracking(inputArray, v, visited, solved);
- }
- return solved;
- }
- void backtracking(std::vector<std::string> &inputArray, int currentVertex, std::vector<bool> &visited, bool &solved)
- {
- const size_t inputArraySize = inputArray.size();
- if (1 == std::count(visited.begin(), visited.end(), false))
- {
- solved = true;
- }
- // current vertex can go to ANY STRING that is not visited YET!
- else if (!visited[currentVertex] && !solved)
- {
- visited[currentVertex] = true;
- // trying to find who is a neighbor on our abstract graph - Any inputArray[curNeighbor] who has mismatches = 1 with inputArray[currentVertex] string
- // important thing - we can pick only one, if we go backtrack then we do not! choose that curNeighbor but we choose different one
- for (int currentNeighbor{}; currentNeighbor < inputArraySize; ++currentNeighbor)
- {
- // if I visited already this neighbor in current path or it's me... then skip this iteration
- if (currentNeighbor == currentVertex || visited[currentNeighbor])
- continue;
- // now try to find if the current contender has mismatch = 1 with currentVertex
- int misMatches = 0;
- const size_t sizeOfCurrentString = inputArray[currentVertex].size();
- for (int idx{}; idx < sizeOfCurrentString && misMatches <= 1; ++idx)
- {
- if (inputArray[currentVertex][idx] != inputArray[currentNeighbor][idx])
- ++misMatches;
- }
- // might be a good for solution
- if (misMatches == 1)
- {
- backtracking(inputArray, currentNeighbor, visited, solved);
- visited[currentNeighbor] = false; // backtrack!!!
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement