动态规划:利用WarShell算法求有向图的传递闭包
1using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace ConsoleApplication47
6{
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 WarShall ws = new WarShall(4);
12
13 ws.SetVaule(0, 1, true);
14 ws.SetVaule(1, 3, true);
15 ws.SetVaule(3, 0, true);
16 ws.SetVaule(3, 2, true);
17
18 Console.WriteLine("Before:");
19
20 ws.Print();
21
22 bool[][] result = ws.GetMatrix();
23
24 Console.WriteLine("After:");
25
26 ws.Print();
27
28 }
29
30 class WarShall
31 {
32 bool[][] _matrix;
33
34 public WarShall(int n)
35 {
36 _matrix = new bool[n][];
37
38 for (int i = 0; i < n; i++)
39 {
40 _matrix[i] = new bool[n];
41 }
42 }
43
44 public void SetVaule(int x, int y, bool vaule)
45 {
46 _matrix[x][y] = vaule;
47 }
48
49 public bool[][] Matrix
50 {
51 get
52 {
53 return _matrix;
54 }
55 }
56
57 public bool[][] GetMatrix()
58 {
59 for (int i = 0; i < _matrix.Length; i++)
60 {
61 for (int x = 0; x < _matrix.Length; x++)
62 {
63 if (x == i)
64 {
65 continue;
66 }
67
68 for (int y = 0; y < _matrix.Length; y++)
69 {
70 if (y == i)
71 {
72 continue;
73 }
74
75 if (_matrix[x][i] && _matrix[i][y])
76 {
77 _matrix[x][y] = true;
78 }
79 }
80 }
81 }
82
83
84 return _matrix;
85 }
86
87 public void Print()
88 {
89 for (int i = 0; i < _matrix.Length; i++)
90 {
91 bool[] s = _matrix[i];
92 for (int j = 0; j < s.Length; j++)
93 {
94 Console.Write(s[j]);
95 Console.Write(" ");
96 }
97 Console.WriteLine();
98 }
99 }
100 }
101 }
102}
103
2using System.Collections.Generic;
3using System.Text;
4
5namespace ConsoleApplication47
6{
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 WarShall ws = new WarShall(4);
12
13 ws.SetVaule(0, 1, true);
14 ws.SetVaule(1, 3, true);
15 ws.SetVaule(3, 0, true);
16 ws.SetVaule(3, 2, true);
17
18 Console.WriteLine("Before:");
19
20 ws.Print();
21
22 bool[][] result = ws.GetMatrix();
23
24 Console.WriteLine("After:");
25
26 ws.Print();
27
28 }
29
30 class WarShall
31 {
32 bool[][] _matrix;
33
34 public WarShall(int n)
35 {
36 _matrix = new bool[n][];
37
38 for (int i = 0; i < n; i++)
39 {
40 _matrix[i] = new bool[n];
41 }
42 }
43
44 public void SetVaule(int x, int y, bool vaule)
45 {
46 _matrix[x][y] = vaule;
47 }
48
49 public bool[][] Matrix
50 {
51 get
52 {
53 return _matrix;
54 }
55 }
56
57 public bool[][] GetMatrix()
58 {
59 for (int i = 0; i < _matrix.Length; i++)
60 {
61 for (int x = 0; x < _matrix.Length; x++)
62 {
63 if (x == i)
64 {
65 continue;
66 }
67
68 for (int y = 0; y < _matrix.Length; y++)
69 {
70 if (y == i)
71 {
72 continue;
73 }
74
75 if (_matrix[x][i] && _matrix[i][y])
76 {
77 _matrix[x][y] = true;
78 }
79 }
80 }
81 }
82
83
84 return _matrix;
85 }
86
87 public void Print()
88 {
89 for (int i = 0; i < _matrix.Length; i++)
90 {
91 bool[] s = _matrix[i];
92 for (int j = 0; j < s.Length; j++)
93 {
94 Console.Write(s[j]);
95 Console.Write(" ");
96 }
97 Console.WriteLine();
98 }
99 }
100 }
101 }
102}
103