成语接龙,哈希表神马的最给力了。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ConsoleApplication1
{
public class Idiom
{
public static Dictionary<Char, List<int>> Dict = new Dictionary<char, List<int>>();
public static List<Idiom> IdiomList = new List<Idiom>();
static Idiom()
{
string[] Arr= File.ReadAllLines(Environment.CurrentDirectory + @"\idiom.txt",Encoding.UTF8);
for (int i = 0; i < Arr.Length; i++)
{
Idiom I
= new Idiom(i, Arr[i]);
IdiomList.Add(I);
if (!Dict.ContainsKey(I.Head))
{
Dict.Add(I.Head,
new List<int>());
}
Dict[I.Head].Add(I.ID);
}
}
public Idiom(int id,string word )
{
ID
= id;
Word
= word;
char[] C = word.ToCharArray();
Head
= C[0];
Tail
= C[word.Length - 1];
}
public string Word;
public int ID;
public char Tail;
public char Head;
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
public class Dragon
{
public Dragon(Idiom I )
{
Body.Add(I.ID);
Tail
= I.Tail;
}
public Dragon(Dragon D, Idiom I)
{
Body
= new HashSet<int>(D.Body);
Body.Add(I.ID);
Tail
= I.Tail;
}
public HashSet<int> Body = new HashSet<int>();
public Char Tail{get;set;}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace ConsoleApplication1
{
class Program
{

static Stopwatch SW = new Stopwatch();
static bool Finish = true;
static Dragon maxDragon = null;
static int maxLength = 1;
static void Main(string[] args)
{
SW.Start();
char input = '';
if (Idiom.Dict.ContainsKey(input))
{
List
<int> First = Idiom.Dict[input];
foreach (int i in First)
{
Dragon D
= new Dragon(Idiom.IdiomList[i]);
if (Finish) { maxDragon = D; Finish = false; }
DFS(D);
}
}
else
{
Console.WriteLine(
"输入的词不存在");
}

Console.Read();
}

private static void DFS(Dragon D)
{

if (SW.ElapsedMilliseconds > 1000 && !Finish)
{
SW.Stop();

if (maxDragon.Body.Count == maxLength)
{
foreach (int i in maxDragon.Body)
{
Console.Write(Idiom.IdiomList[i].Word
+ ",");
}
Console.WriteLine(maxDragon.Body.Count);
}

Finish
= true;
return;
}
if (Finish) { return; }
if (Idiom.Dict.ContainsKey(D.Tail))
{
foreach (int i in Idiom.Dict[D.Tail])
{
if (!D.Body.Contains(i))//无环
{
Dragon newDragon
= new Dragon(D, Idiom.IdiomList[i]);
if (newDragon.Body.Count > maxDragon.Body.Count)
{
maxDragon
= newDragon;
maxLength
=newDragon.Body.Count;
}
DFS(newDragon);
}
}
}
}
}
}

posted @ 2011-07-01 19:19  CSDN大笨狼  阅读(376)  评论(1编辑  收藏  举报