本文实例为大家分享了C#深度优先搜索算法的具体代码,供大家参考,具体内容如下
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
|
//论文要用到其改进算法,在此先demo测试一下 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DFS { class Program { public int [,] map = new int [100, 100]; public int [] road = new int [120]; public int n, x, y; public int m = 1; public int [] visited = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static void Main( string [] args) { Program pro = new DFS.Program(); int i, j; pro.n = int .Parse(Console.ReadLine()); pro.x= int .Parse(Console.ReadLine()); pro.y= int .Parse(Console.ReadLine()); for (i = 0; i < pro.n; i++) { for (j = 0; j < pro.n; j++) { pro.map[i,j]= int .Parse(Console.ReadLine()); } } pro.road[0] = pro.x; pro.dfs(pro.x); } public void dfs( int p) { visited[p] = 1; int i, j; for (i = 0; i < n; i++) { if (map[p,i] == 1 && visited[i] == 0) { if (i == y) ///如果深搜到了终点,就输出刚才经过的路径 { for (j = 0; j < m; j++) { Console.WriteLine( "{0}" , road[j]); } Console.WriteLine( "{0}\r\n" , y); } else ///如果该点不是终点 { map[p,i] = 0; road[m] = i; ///将该点存起来 m++; dfs(i); ///接着深搜 map[p,i] = 1; visited[i] = 0; m--; } } } } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。