Skip to content

Commit 0131b81

Browse files
author
tianqing.liang
committed
图的邻接矩阵
1 parent f173cd0 commit 0131b81

File tree

4 files changed

+94
-1
lines changed

4 files changed

+94
-1
lines changed

25-GraphBascis/AdjMatrix.dart

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import 'dart:io';
2+
3+
/**
4+
* 图的邻接矩阵表示方式
5+
*
6+
* 注:
7+
* 由于原构造方法需要读取文件
8+
* dart语言中读取文件是异步方法
9+
* dart语言中构造方法是不允许异步
10+
*
11+
* 所以无法按照原有格式实现,故更换方式
12+
*
13+
* 先读取文件,将相应数据赋值
14+
*/
15+
class AdjMatrix {
16+
int? _V;//图的顶点数量
17+
int? _E;//图的边的数量
18+
List? _adj;//邻接矩阵
19+
20+
21+
AdjMatrix( V,E,List list) {
22+
_V = V;
23+
_E = E ;
24+
25+
_adj = List.generate(V, (_)=>List.generate(V,(_)=> 0),growable: false);
26+
for(int i =1;i<E;i++){
27+
int a = int.parse(list[i].split(" ")[0]);
28+
int b = int.parse(list[i].split(" ")[1]);
29+
_adj![a][b] = 1;
30+
_adj![b][a] = 1;
31+
}
32+
}
33+
34+
@override
35+
String toString() {
36+
StringBuffer sb = new StringBuffer();
37+
sb.write("V = $_V, E = $_E\n");
38+
for (int i = 0; i < _V!; i ++) {
39+
for (int j = 0; j < _V!; j ++)
40+
sb.write("${_adj![i][j]} ");
41+
sb.write('\n');
42+
}
43+
return sb.toString();
44+
}
45+
46+
47+
}
48+
49+
void main() async {
50+
File content = File("g.txt");
51+
List<String> list = await content.readAsLines();
52+
//读取到文件的顶点数量以及
53+
print(list[0].split(" ")[0]);
54+
print(list[0].split(" ")[1]);
55+
int v = int.parse(list[0].split(" ")[0]) ;
56+
int e = int.parse(list[0].split(" ")[1]) ;
57+
//
58+
AdjMatrix adjMatrix = AdjMatrix(v, e, list);
59+
print(adjMatrix);
60+
61+
}

25-GraphBascis/FileOperator.dart

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import 'dart:io';
2+
import 'dart:convert';
3+
4+
/**
5+
* 文件操作类
6+
*/
7+
class FileOperator{
8+
9+
static Future<List> getFileString(String filename) async{
10+
Stream<List<int>> content = File(filename).openRead();
11+
List<String> lines = await content.transform(utf8.decoder).transform(LineSplitter()).toList();
12+
var words = [];
13+
for(int i = 0;i<lines.length;i++){
14+
words.addAll(lines[i].split(" ").toList());
15+
}
16+
words.removeWhere((element) => element == "");
17+
return words;
18+
}
19+
}

25-GraphBascis/g.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
7 9
2+
0 1
3+
0 3
4+
1 2
5+
1 6
6+
2 3
7+
2 5
8+
3 4
9+
4 5
10+
5 6

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# AlgorithmAndDataArchitecture
22

33
<h2>使用Flutter的Dart语言重写数据结构与算法</h2>
4-
54
1. 线性搜索
65
2. 选择排序
76
3. 插入排序
@@ -27,6 +26,10 @@
2726
23. MSD排序,桶排序
2827
24. 字符串匹配
2928

29+
<h3>图相关的数据结构与算法</h3>
30+
1. 图的邻接矩阵
31+
32+
3033
#### 后续更新
3134
1. 将图相关的数据结构与算法用dart语言重新实现
3235

0 commit comments

Comments
 (0)