CSharp · Console
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public class WebParser
{
private static Dictionary<string, List<string>> SampleTreeUrl = new Dictionary<string, List<string>>()
{
{
"http://blog.unilecs.ru/tasks/arrays",
new List<string>() {
"http://blog.unilecs.ru",
"http://blog.unilecs.ru/tasks"
}
},
{
"http://blog.unilecs.ru",
new List<string>() {
"http://blog.unilecs.ru/puzzles",
"http://blog.supercode.ru/tasks"
}
},
{
"http://blog.supercode.ru/tasks/arrays",
new List<string>() {
"http://blog.supercode.ru",
"http://blog.supercode.ru/tasks"
}
},
{
"http://blog.supercode.ru",
new List<string>() {
"http://blog.supercode.ru/puzzles",
"http://blog.unilecs.ru/tasks/arrays"
}
},
};
public List<string> GetUrls(string startUrl)
{
if (!SampleTreeUrl.ContainsKey(startUrl))
return new List<string>();
return SampleTreeUrl[startUrl];
}
}
public class WebCrawler
{
private readonly WebParser webParser;
public string StartHost = string.Empty;
public WebCrawler()
{
this.webParser = new WebParser();
}
public IList<string> Crawl(string startUrl)
{
StartHost = ParseHost(startUrl);
var result = new HashSet<string>();
DFS(startUrl, result);
return result.ToList();
}
public void DFS(string url, HashSet<string> result)
{
if (StartHost != ParseHost(url) || result.Contains(url))
{
return;
}
result.Add(url);
foreach (string cUrl in this.webParser.GetUrls(url))
{
DFS(cUrl, result);
}
}
public static string ParseHost(string url)
{
return new Uri(url).Host;
}
}
static void ShowList(IList<string> list, string prefix = "List")
{
Console.WriteLine(string.Format("{0}: {1}", prefix, string.Join(", ", list)));
}
public static void Main()
{
Console.WriteLine("UniLecs");
// tests
var webCrawler = new WebCrawler();
ShowList(webCrawler.Crawl("http://blog.unilecs.ru/tasks/arrays"));
ShowList(webCrawler.Crawl("http://blog.supercode.ru/tasks/arrays"));
}
}