一道典型的 dfs(回溯):
使用vector<string>保存单词,sort一下;
dfs的时候,单词的首字母先用二分查找找到上下界,缩小范围;
vis数组:0,1保存状态;
#pragma warning(disable:4996)
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
using namespace std;
vector<string> vec;
bool vis[1000];
bool flag;
char first, last;
int lowBound(char ch)
{
int low = 0;
int high = vec.size() - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (ch<vec[mid].at(0))
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return low;
}
void dfs(char first)
{
if (first == last)
{
flag = 1;
return;
}
int m = lowBound(first - 1);
int n = lowBound(first + 1);
for (int i = m; i<n; ++i)
{