-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchainedWords.cpp
More file actions
78 lines (62 loc) · 1.65 KB
/
chainedWords.cpp
File metadata and controls
78 lines (62 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// Created by Mayank Parasar on 2020-01-31.
//
/*
* Two words can be 'chained' if the last character of the first word is the same as
* the first character of the second word.
Given a list of words, determine if there is a way to 'chain' all the words in a circle.
Example:
Input: ['eggs', 'karat', 'apple', 'snack', 'tuna']
Output: True*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//struct node {
// string str;
// bool visited;
//
// node* next;
//
// node(string str_) : str(str_), visited(false)
// {}
//};
void check_chained(vector<string>& array, vector<bool>& visited, int idx) { // this function will populate this vector
string word = array[idx];
char c = word[word.length()-1];
// scan the whole vector to find the word whoes first letter is 'c'
int ii;
for(ii=0; ii < array.size(); ii++) {
if(array[ii][0] == c) {
if(visited[ii] == false) {
visited[ii] = true;
}
else {
return;
}
break;
}
}
if(ii < array.size()) {
check_chained(array, visited, ii);
return;
}
return;
}
int main() {
vector<string> array = {"eggs", "karat", "apple", "snack", "tuna"};
vector<bool> visited(array.size(), false);
check_chained(array, visited, 0); // starting with first element
int ii;
for(ii = 0; ii < visited.size(); ii++) {
if(visited[ii])
continue;
else
break;
}
if(ii == visited.size())
cout << "word list is chained";
else
cout << "word list is not chained";
return 0;
}