Approach
Breadth-first search
For Web Crawler, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 40 lines of C++ from the credited upstream file 1236.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 2 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/**2 * 3 * 4 * class HtmlParser {5 * public:6 * vector<string> getUrls(string url);7 * };8 */9 10class Solution {11 public:12 vector<string> crawl(string startUrl, HtmlParser htmlParser) {13 queue<string> q{{startUrl}};14 unordered_set<string> seen{{startUrl}};15 const string& hostname = getHostname(startUrl);16 17 while (!q.empty()) {18 const string currUrl = q.front();19 q.pop();20 for (const string& url : htmlParser.getUrls(currUrl)) {21 if (seen.contains(url))22 continue;23 if (url.find(hostname) != string::npos) {24 q.push(url);25 seen.insert(url);26 }27 }28 }29 30 return {seen.begin(), seen.end()};31 }32 33 private:34 string getHostname(const string& url) {35 const int firstSlash = url.find_first_of('/');36 const int thirdSlash = url.find_first_of('/', firstSlash + 2);37 return url.substr(firstSlash + 2, thirdSlash - firstSlash - 2);38 }39};40