Merge remote-tracking branch 'Graphs_dart/bfs&dfs'

This commit is contained in:
Морозов Андрей 2021-11-10 19:48:00 +04:00
commit 9024c24c4c
5 changed files with 604 additions and 459 deletions

View File

@ -51,10 +51,9 @@ void main(List<String> arguments) {
List<Graphs> graphs = <Graphs>[]; List<Graphs> graphs = <Graphs>[];
String name; String name;
String str = ""; String str = "";
Separators sep = Separators();
while (deistvie != 0) { while (deistvie != 0) {
stdout.write( stdout.write(
"1 - создать граф, 2 - удалить граф, 3 - добавить в граф вершину,\n4 - удалить вершину, 5 - добавить ребро/дугу, 6 - удалить ребро/дугу,\n7 - вывести граф на экран, 8 - вывести граф в файл, 0 - выход\nDeistvie: "); "1 - создать граф, 2 - удалить граф, 3 - добавить в граф вершину,\n4 - удалить вершину, 5 - добавить ребро/дугу, 6 - удалить ребро/дугу,\n7 - вывести граф на экран, 8 - вывести граф в файл, 9 - обход в ширину,\n0 - выход\nDeistvie: ");
deistvie = getIntLine(); deistvie = getIntLine();
switch (deistvie) { switch (deistvie) {
case 1: case 1:
@ -112,9 +111,9 @@ void main(List<String> arguments) {
List<int> inn = <int>[]; List<int> inn = <int>[];
List<int> len = <int>[]; List<int> len = <int>[];
List<String> a = str.split(sep.space); List<String> a = str.split(Separators.space);
for (var splitted in a) { for (var splitted in a) {
var dt = splitted.split(sep.dotToLength); var dt = splitted.split(Separators.dotToLength);
if (dt.length == 2) { if (dt.length == 2) {
inn.add(int.parse(dt[0])); inn.add(int.parse(dt[0]));
len.add(int.parse(dt[1])); len.add(int.parse(dt[1]));
@ -157,13 +156,13 @@ void main(List<String> arguments) {
stdout.write("Имя вершины: "); stdout.write("Имя вершины: ");
String dotName = getStrLine(); String dotName = getStrLine();
stdout.write( /*stdout.write(
"Ввод: *куда*|*вес* через пробел. Если граф не взвешенный, то *вес* можно не указывать.\nВершина cмежна с: "); "Ввод: *куда*|*вес* через пробел. Если граф не взвешенный, то *вес* можно не указывать.\nВершина cмежна с: ");
str = getStrLine(); str = getStrLine();
List<String> a = str.split(sep.space); List<String> a = str.split(Separators.space);
for (var splitted in a) { for (var splitted in a) {
var dt = splitted.split(sep.dotToLength); var dt = splitted.split(Separators.dotToLength);
if (dt.length == 2) { if (dt.length == 2) {
inn.add(int.parse(dt[0])); inn.add(int.parse(dt[0]));
len.add(int.parse(dt[1])); len.add(int.parse(dt[1]));
@ -171,12 +170,12 @@ void main(List<String> arguments) {
inn.add(int.parse(splitted)); inn.add(int.parse(splitted));
len.add(0); len.add(0);
} }
} }*/
printGraphsName(graphs); printGraphsName(graphs);
stdout.write("Вставка в графа с номером: "); stdout.write("Вставка в графа с номером: ");
int y = getIntLine(); int y = getIntLine();
if (y >= 0 && y < graphs.length) { if (y >= 0 && y < graphs.length) {
graphs[y].addDotFromToLists(dotName, inn, len); graphs[y].addIsolated(dotName);
} else { } else {
print("Не найден граф с таким номером"); print("Не найден граф с таким номером");
} }
@ -244,7 +243,7 @@ void main(List<String> arguments) {
num = graphs[y].getDotAmount(); num = graphs[y].getDotAmount();
stdout.write( stdout.write(
"Количество вершин: $num. Введите через пробел 2 вершины, между которыми удалить ребро: "); "Количество вершин: $num. Введите через пробел 2 вершины, между которыми удалить ребро: ");
List<String> x = getStrLine().split(sep.space); List<String> x = getStrLine().split(Separators.space);
x1 = int.parse(x[0]); x1 = int.parse(x[0]);
x2 = int.parse(x[1]); x2 = int.parse(x[1]);
if (x1 >= 0 && x1 < num && x2 >= 0 && x2 < num) { if (x1 >= 0 && x1 < num && x2 >= 0 && x2 < num) {
@ -286,6 +285,29 @@ void main(List<String> arguments) {
} }
break; break;
} }
case 9:
{
int num = graphs.length;
printGraphsName(graphs);
stdout.write("Работаем в графе с номером: ");
int y = getIntLine();
if (y >= 0 && y < num) {
graphs[y].printG();
num = graphs[y].getDotAmount();
stdout.write("Вершина, из которой выходят: ");
int x1 = getIntLine();
stdout.write("Вершина, в которую идут: ");
int x2 = getIntLine();
if (x1 >= 0 && x1 <= num && x2 >= 0 && x2 <= num) {
print("BFS: ${graphs[y].bfsPath(x1, x2)}");
} else {
print("Не найдены введеные вершины в графе\n");
}
} else {
print("Не найден граф с таким номером");
}
break;
}
case 0: case 0:
getStrLine(); getStrLine();
exit(0); exit(0);

View File

@ -1,15 +1,15 @@
import 'dart:io'; import 'dart:io';
class Separators { class Separators {
final String dotToConnections = ": "; static const String dotToConnections = ": ";
final String dotToLength = "|"; static const String dotToLength = "|";
final String space = " "; static const String space = " ";
final String hasLength = "Взвешенный\n"; static const String hasLength = "Взвешенный";
final String hasNoLength = "НеВзвешенный\n"; static const String hasNoLength = "НеВзвешенный";
final String isOriented = "Ориентированный\n"; static const String isOriented = "Ориентированный";
final String isNotOriented = "НеОриентированный\n"; static const String isNotOriented = "НеОриентированный";
final String nL = "\n"; static const String nL = "\n";
final String end = "END"; static const String end = "END";
Separators(); Separators();
} }
@ -25,6 +25,7 @@ class Dot {
String getName() => _name; String getName() => _name;
bool hasConnection(int n) => _ln.containsKey(n); bool hasConnection(int n) => _ln.containsKey(n);
Map<int, int> getL() => _ln; Map<int, int> getL() => _ln;
int getLength(int x) { int getLength(int x) {
if (hasConnection(x)) { if (hasConnection(x)) {
return _ln[x]!; return _ln[x]!;
@ -53,9 +54,9 @@ class Dot {
} }
//******Constructor****** //******Constructor******
Dot() { Dot([String name = "Undefined", int n = -1]) {
_name = "Undefined"; _name = name;
num = -1; num = n;
_ln = <int, int>{}; _ln = <int, int>{};
} }
Dot.fromTwoLists(String name, List<int> num0, List<int> length, Dot.fromTwoLists(String name, List<int> num0, List<int> length,
@ -97,11 +98,9 @@ class Graphs {
bool _oriented = false; //Ориентированность bool _oriented = false; //Ориентированность
//*********************Add************************ //*********************Add************************
bool addDot(Dot a) { String? addDot(Dot a) {
if (getNumByName(a.getName()) != null) { if (getNumByName(a.getName()) != null) {
print( return ("Dot name \"${a.getName()}\" already in use. Change name or use addPath");
"Dot name ${a.getName()} already in use. Change name or use addPath");
return false;
} }
_amount++; _amount++;
a.num = _amount; a.num = _amount;
@ -109,7 +108,7 @@ class Graphs {
_syncNameTable(); _syncNameTable();
checkDots(false); checkDots(false);
if (!_oriented) _fullFix(); if (!_oriented) _fullFix();
return true; return null;
} }
bool addDotFromToLists(String name, List<int> num0, List<int> length, bool addDotFromToLists(String name, List<int> num0, List<int> length,
@ -129,37 +128,40 @@ class Graphs {
return true; return true;
} }
bool addIsolated(String name) { String? addIsolated(String name) {
var o = addDot(Dot.fromTwoLists(name, [], [])); var res = addDot(Dot.fromTwoLists(name, [], []));
_syncNameTable(); _syncNameTable();
return o; return res;
} }
bool addPath(int from, int to, [int len = 0]) { String? addPath(int from, int to, [int len = 0]) {
if (from <= 0 || from > _amount || to <= 0 && to > _amount) { if (from <= 0 || from > _amount || to <= 0 && to > _amount) {
return false; return "Index out of range. Have dots 1..$_amount";
} }
_dots[from - 1].addPath(to, len); _dots[from - 1].addPath(to, len);
if (!_oriented) { if (!_oriented) {
_dots[to - 1].addPath(from, len); _dots[to - 1].addPath(from, len);
} }
return true; return null;
} }
//*********************Add************************ //*********************Add************************
//*********Delete********* //*********Delete*********
bool delPath(int from, int to) { String? delPath(int from, int to) {
if (from <= 0 || from > _amount || to <= 0 && to > _amount) { if (from <= 0 || from > _amount || to <= 0 && to > _amount) {
return false; return "Can't find specified path";
} }
_dots[from - 1].delPath(to); _dots[from - 1].delPath(to);
if (!_oriented) { if (!_oriented) {
_dots[to - 1].delPath(from); _dots[to - 1].delPath(from);
} }
return true; return null;
} }
bool delDot(int inn) { String? delDot(int inn) {
if (inn > _amount || inn < 1) {
return "Index out of range. Allowed 1..$_amount";
}
List<int> toDel = <int>[]; List<int> toDel = <int>[];
for (int i in _dots[inn - 1].getL().keys) { for (int i in _dots[inn - 1].getL().keys) {
toDel.add(i); toDel.add(i);
@ -171,7 +173,13 @@ class Graphs {
_syncNum(); _syncNum();
_syncNameTable(); _syncNameTable();
_fixAfterDel(inn); _fixAfterDel(inn);
return true; return null;
}
void flushData() {
_dots = <Dot>[];
_amount = 0;
_nameTable = <int, String>{};
} }
//*********Delete********* //*********Delete*********
@ -241,12 +249,121 @@ class Graphs {
} }
//******Helper******* //******Helper*******
//*****Setters*******
void setName(String name) => _name = name;
String? flipUseOrientation() {
if (_amount != 0) {
return "Can change use of orientation only in empty graph";
}
_oriented = !_oriented;
return null;
}
String? flipUseLength() {
if (_amount != 0) {
return "Can change use of length only in empty graph";
}
_useLength = !_useLength;
return null;
}
String? replaceDataFromFile(String path) {
File file = File(path);
List<String> lines = file.readAsLinesSync();
if (lines.length < 3) {
return "Not enough lines in file";
}
String name = lines.removeAt(0);
bool oriented;
switch (lines.removeAt(0)) {
case Separators.isOriented:
oriented = true;
break;
case Separators.isNotOriented:
oriented = false;
break;
default:
return "Error on parsing \"IsOriented\"";
}
bool useLength;
switch (lines.removeAt(0).trim()) {
case Separators.hasLength:
useLength = true;
break;
case Separators.hasNoLength:
useLength = false;
break;
default:
return "Error on parsing \"HasLength\"";
}
List<Dot> dots = <Dot>[];
for (var l in lines) {
l = l.trimRight();
if (l != Separators.end) {
var spl = l.split(Separators.space);
List<int> dot = <int>[];
List<int> len = <int>[];
String name = spl.removeAt(0);
name = name.substring(0, name.length - 1);
for (var splitted in spl) {
if (splitted != "") {
var dt = splitted.split(Separators.dotToLength);
if (dt.length == 2) {
int? parsed = int.tryParse(dt[0]);
if (parsed == null) {
return "Error while parsing file\nin parsing int in \"${dt[0]}\"";
}
dot.add(parsed);
if (useLength) {
parsed = int.tryParse(dt[1]);
if (parsed == null) {
return "Error while parsing file\nin parsing int in \"${dt[1]}\"";
}
len.add(parsed);
} else {
len.add(0);
}
} else if (dt.length == 1) {
int? parsed = int.tryParse(splitted);
if (parsed == null) {
return "Error while parsing file\nin parsing int in \"$splitted\"";
}
dot.add(parsed);
len.add(0);
}
}
}
dots.add(Dot.fromTwoLists(name, dot, len));
}
}
_name = name;
_oriented = oriented;
_useLength = useLength;
_dots = dots;
_syncNum();
_syncNameTable();
if (!_oriented) _fullFix();
return null;
}
//*****Setters*******
//*****Getters******* //*****Getters*******
bool getDoubleSided() => _oriented; bool getDoubleSidedBool() => _oriented;
bool getUseLength() => _useLength; String getDoubleSidedStr() {
if (_oriented) return Separators.isOriented;
return Separators.isNotOriented;
}
bool getUseLengthBool() => _useLength;
String getUseLengthStr() {
if (_useLength) return Separators.hasLength;
return Separators.hasNoLength;
}
List<Dot> getDots() => _dots; List<Dot> getDots() => _dots;
String getName() => _name; String getName() => _name;
String? getNameByNum(int n) => _nameTable[n]; String? getNameByNum(int n) => _nameTable[n];
Map<int, String> getNameTable() => _nameTable;
int getDotAmount() => _dots.length; int getDotAmount() => _dots.length;
int? getNumByName(String n) { int? getNumByName(String n) {
for (var i in _nameTable.keys) { for (var i in _nameTable.keys) {
@ -282,6 +399,23 @@ class Graphs {
} }
return out; return out;
} }
/*List<Dot> getNoRepeatDots() {
List<Dot> ret = <Dot>[];
for (int i = 0; i < _amount; i++) {
ret.add(Dot(_dots[i].getName(), _dots[i].num));
}
for (int i = 0; i < _amount; i++) {
for (int j in _dots[i].getL().keys) {
if (!ret[j - 1].hasConnection(i + 1) && !ret[i].hasConnection(j) ||
i == j) {
var len = _dots[i].getLength(j);
ret[i].addPath(j, len);
}
}
}
return ret;
}*/
//*****Getters******* //*****Getters*******
//******Print****** //******Print******
@ -303,31 +437,34 @@ class Graphs {
} }
void printToFile(String name) { void printToFile(String name) {
Separators sep = Separators();
var file = File(name); var file = File(name);
file.writeAsStringSync("$_name\n"); file.writeAsStringSync("$_name\n");
if (_oriented) { if (_oriented) {
file.writeAsStringSync(sep.isOriented, mode: FileMode.append); file.writeAsStringSync("${Separators.isOriented}\n",
mode: FileMode.append);
} else { } else {
file.writeAsStringSync(sep.isNotOriented, mode: FileMode.append); file.writeAsStringSync("${Separators.isNotOriented}\n",
mode: FileMode.append);
} }
if (_useLength) { if (_useLength) {
file.writeAsStringSync(sep.hasLength, mode: FileMode.append); file.writeAsStringSync("${Separators.hasLength}\n",
mode: FileMode.append);
} else { } else {
file.writeAsStringSync(sep.hasNoLength, mode: FileMode.append); file.writeAsStringSync("${Separators.hasNoLength}\n",
mode: FileMode.append);
} }
for (int i = 0; i < _amount; i++) { for (int i = 0; i < _amount; i++) {
file.writeAsStringSync((i + 1).toString() + sep.dotToConnections, file.writeAsStringSync((i + 1).toString() + Separators.dotToConnections,
mode: FileMode.append); mode: FileMode.append);
var d = _dots[i].getL(); var d = _dots[i].getL();
for (var j in d.keys) { for (var j in d.keys) {
file.writeAsStringSync( file.writeAsStringSync(
j.toString() + sep.dotToLength + d[j].toString() + " ", j.toString() + Separators.dotToLength + d[j].toString() + " ",
mode: FileMode.append); mode: FileMode.append);
} }
file.writeAsStringSync(sep.nL, mode: FileMode.append); file.writeAsStringSync(Separators.nL, mode: FileMode.append);
} }
file.writeAsStringSync(sep.end, mode: FileMode.append); file.writeAsStringSync(Separators.end, mode: FileMode.append);
} }
//******Print****** //******Print******
@ -353,22 +490,22 @@ class Graphs {
if (!_oriented) _fullFix(); if (!_oriented) _fullFix();
} }
Graphs.fromFile(String path) { Graphs.fromFile(String path) {
Separators sep = Separators(); replaceDataFromFile(path);
File file = File(path); /*File file = File(path);
List<String> lines = file.readAsLinesSync(); List<String> lines = file.readAsLinesSync();
_name = lines.removeAt(0); _name = lines.removeAt(0);
_oriented = lines.removeAt(0) == sep.isOriented.trim(); _oriented = lines.removeAt(0) == Separators.isOriented.trim();
_useLength = lines.removeAt(0) == sep.hasLength.trim(); _useLength = lines.removeAt(0) == Separators.hasLength.trim();
_dots = <Dot>[]; _dots = <Dot>[];
for (var l in lines) { for (var l in lines) {
if (l != sep.end) { if (l != Separators.end) {
var spl = l.split(sep.space); var spl = l.split(Separators.space);
List<int> dot = <int>[]; List<int> dot = <int>[];
List<int> len = <int>[]; List<int> len = <int>[];
String name = spl.removeAt(0); String name = spl.removeAt(0);
name = name.substring(0, name.length - 1); name = name.substring(0, name.length - 1);
for (var splitted in spl) { for (var splitted in spl) {
var dt = splitted.split(sep.dotToLength); var dt = splitted.split(Separators.dotToLength);
if (dt.length == 2) { if (dt.length == 2) {
dot.add(int.parse(dt[0])); dot.add(int.parse(dt[0]));
if (_useLength) { if (_useLength) {
@ -386,7 +523,7 @@ class Graphs {
} }
_syncNum(); _syncNum();
_syncNameTable(); _syncNameTable();
if (!_oriented) _fullFix(); if (!_oriented) _fullFix();*/
} }
//*******Constructor******** //*******Constructor********
@ -394,14 +531,14 @@ class Graphs {
Graphs.clone(Graphs a) { Graphs.clone(Graphs a) {
_name = a.getName(); _name = a.getName();
_dots = a.getDots(); _dots = a.getDots();
_oriented = a.getDoubleSided(); _oriented = a.getDoubleSidedBool();
_useLength = a.getUseLength(); _useLength = a.getUseLengthBool();
_amount = _dots.length; _amount = _dots.length;
_syncNameTable(); _syncNameTable();
} }
//************Алгоритмы************ //************Алгоритмы************
bool bfsHasPath(int startDot, int goalDot) { /* bool bfsHasPath(int startDot, int goalDot) {
// обход в ширину // обход в ширину
startDot--; startDot--;
goalDot--; goalDot--;
@ -428,9 +565,10 @@ class Graphs {
} }
} }
return false; // Целевой узел недостижим return false; // Целевой узел недостижим
} }*/
List<int>? bfsPath(int startDot, int goalDot) { List<int>? bfsPath(int startDot, int goalDot) {
if (startDot == goalDot) return [startDot];
//if (!bfsHasPath(startDot, goalDot)) return null; //if (!bfsHasPath(startDot, goalDot)) return null;
startDot--; startDot--;
goalDot--; goalDot--;
@ -470,7 +608,6 @@ class Graphs {
//Восстановим кратчайший путь //Восстановим кратчайший путь
//Для восстановления пути пройдём его в обратном порядке, и развернём. //Для восстановления пути пройдём его в обратном порядке, и развернём.
List<int> path = <int>[]; List<int> path = <int>[];
int cur = goalDot; //текущая вершина пути int cur = goalDot; //текущая вершина пути
@ -493,21 +630,25 @@ class Graphs {
List<bool>? dfsIterative(int v) { List<bool>? dfsIterative(int v) {
v--; v--;
//List<int>? pos = <int>[];
List<bool> label = <bool>[]; List<bool> label = <bool>[];
for (int i = 0; i < _amount; i++) { for (int i = 0; i < _amount; i++) {
label.add(false); label.add(false);
} }
List<int> stack = <int>[]; List<int> stack = <int>[];
stack.add(v); stack.add(v);
//pos.add(v);
while (stack.isNotEmpty) { while (stack.isNotEmpty) {
v = stack.removeLast(); v = stack.removeLast();
if (!label[v]) { if (!label[v]) {
label[v] = true; label[v] = true;
for (int i in _dots[v].getL().keys) { for (int i in _dots[v].getL().keys) {
stack.add(i - 1); stack.add(i - 1);
//pos.add(i);
} }
} }
} }
//print(pos);
return label; return label;
} }

View File

@ -8,71 +8,85 @@ class CurvePainter extends CustomPainter {
Key? key, Key? key,
required this.graphData, required this.graphData,
required this.bfsPath, required this.bfsPath,
required this.dfsStart, required this.start,
required this.end,
required this.dfsAccessTable, required this.dfsAccessTable,
}); });
List<int>? bfsPath; List<int>? bfsPath;
List<bool>? dfsAccessTable; List<bool>? dfsAccessTable;
int? dfsStart; int? start;
int? end;
Graphs graphData; Graphs graphData;
final double dotRad = 6; final double _dotRad = 6;
final double lineWidth = 2; final double _lineWidth = 1.5;
final Color lineColor = Colors.black; final Color _lineColor = Colors.black;
final double aboveHeight = 5; final double _aboveHeight = 5;
double circleRad = 100; double _circleRad = 100;
final TextStyle textStyle = TextStyle( final TextStyle _textStyle = TextStyle(
color: Colors.green.shade900, color: Colors.red.shade900,
decorationColor: Colors.green.shade900,
decorationThickness: 10,
decorationStyle: TextDecorationStyle.dashed,
fontSize: 20, fontSize: 20,
); );
Map<int, Offset> _off = <int, Offset>{};
void drawLine(Canvas canvas, Offset p1, Offset p2) { void _drawLine(Canvas canvas, Offset p1, Offset p2) {
Paint p = Paint(); Paint p = Paint();
p.color = lineColor; p.color = _lineColor;
p.strokeWidth = lineWidth; p.strokeWidth = _lineWidth;
canvas.drawLine(p1, p2, p); canvas.drawLine(p1, p2, p);
} }
void drawDot(Canvas canvas, Offset p1) { void _drawDot(Canvas canvas, Offset p1, [double plusRad = 0, Color? col]) {
col ??= Colors.yellow.shade900;
var p = Paint(); var p = Paint();
p.color = Colors.yellow.shade900; p.color = col;
p.strokeWidth = lineWidth + 2; p.strokeWidth = _lineWidth + 2;
canvas.drawCircle(p1, dotRad, p); canvas.drawCircle(p1, _dotRad + plusRad, p);
} }
void drawSelfConnect(Canvas canvas, Offset p1) { void _drawSelfConnect(Canvas canvas, Offset p1) {
var p = Paint(); var p = Paint();
p.color = lineColor; p.color = _lineColor;
p.strokeWidth = lineWidth; p.strokeWidth = _lineWidth;
p.style = PaintingStyle.stroke; p.style = PaintingStyle.stroke;
canvas.drawCircle(Offset(p1.dx + dotRad + 20, p1.dy), dotRad + 20, p); canvas.drawCircle(Offset(p1.dx + _dotRad + 20, p1.dy), _dotRad + 20, p);
} }
TextSpan _getTextSpan(String s) => TextSpan(text: s, style: textStyle); TextSpan _getTextSpan(String s) => TextSpan(text: s, style: _textStyle);
TextPainter _getTextPainter(String s) => TextPainter( TextPainter _getTextPainter(String s) => TextPainter(
text: _getTextSpan(s), text: _getTextSpan(s),
textDirection: TextDirection.ltr, textDirection: TextDirection.ltr,
textAlign: TextAlign.center); textAlign: TextAlign.center);
void drawDotNames(Canvas canvas, Offset place, String s) { void _drawDotNames(Canvas canvas, Offset place, String s) {
var textPainter = _getTextPainter(s); var textPainter = _getTextPainter(s);
textPainter.layout(); textPainter.layout();
textPainter.paint( textPainter.paint(
canvas, canvas,
Offset((place.dx - textPainter.width), Offset((place.dx - textPainter.width),
(place.dy - textPainter.height) - aboveHeight)); (place.dy - textPainter.height) - _aboveHeight));
} }
void drawAboveText(Canvas canvas, Offset size, String s) { void _drawDotNum(Canvas canvas, Offset size, String s) {
var textPainter = _getTextPainter(s); var textPainter = TextPainter(
text: TextSpan(
text: s,
style: const TextStyle(
color: Colors.black,
fontSize: 17,
)),
textDirection: TextDirection.ltr,
textAlign: TextAlign.center);
textPainter.layout(); textPainter.layout();
textPainter.paint( textPainter.paint(
canvas, canvas,
Offset((size.dx - textPainter.width), Offset((size.dx - textPainter.width) + 25,
(size.dy - textPainter.height) - aboveHeight)); (size.dy - textPainter.height) + _aboveHeight + 30));
} }
int getHighInputConnections() { int _getHighInputConnections() {
if (graphData.getDots().length != 1 && graphData.getDots().length <= 3) { if (graphData.getDots().length != 1 && graphData.getDots().length <= 3) {
return -1; return -1;
} }
@ -83,17 +97,18 @@ class CurvePainter extends CustomPainter {
return higest; return higest;
} }
Map<int, Offset> getDotPos(int dotsAm, Size size, [int? exclude]) { Map<int, Offset> _getDotPos(int dotsAm, Size size) {
Map<int, Offset> off = <int, Offset>{}; Map<int, Offset> off = <int, Offset>{};
var width = size.width / 2; var width = size.width / 2;
var height = size.height / 2; var height = size.height / 2;
int add = 0; int add = 0;
int h = getHighInputConnections(); int h = _getHighInputConnections();
for (int i = 0; i < dotsAm; i++) { for (int i = 0; i < dotsAm; i++) {
if ((i + 1) != h) { if ((i + 1) != h) {
double x = cos(2 * pi * (i - add) / (dotsAm - add)) * circleRad + width; double x =
cos(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + width;
double y = double y =
sin(2 * pi * (i - add) / (dotsAm - add)) * circleRad + height; sin(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + height;
off[i + 1] = Offset(x, y); off[i + 1] = Offset(x, y);
} else if ((i + 1) == h) { } else if ((i + 1) == h) {
@ -110,7 +125,7 @@ class CurvePainter extends CustomPainter {
return off; return off;
} }
void drawHArrow(Canvas canvas, Size size, Offset from, Offset to, void _drawHArrow(Canvas canvas, Size size, Offset from, Offset to,
[bool doubleSided = false]) { [bool doubleSided = false]) {
Path path; Path path;
@ -120,7 +135,7 @@ class CurvePainter extends CustomPainter {
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round ..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round ..strokeJoin = StrokeJoin.round
..strokeWidth = lineWidth; ..strokeWidth = _lineWidth;
var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) +
(to.dy - from.dy) * (to.dy - from.dy)); (to.dy - from.dy) * (to.dy - from.dy));
@ -131,8 +146,8 @@ class CurvePainter extends CustomPainter {
path.relativeCubicTo( path.relativeCubicTo(
0, 0,
0, 0,
-(from.dx + to.dx) / (length * 2) - 40, -(from.dx + to.dx + length) / (length) - 40,
-(from.dy + to.dy) / (length * 2) - 40, -(from.dy + to.dy + length) / (length) - 40,
to.dx - from.dx, to.dx - from.dx,
to.dy - from.dy); to.dy - from.dy);
path = path =
@ -140,7 +155,7 @@ class CurvePainter extends CustomPainter {
canvas.drawPath(path, paint); canvas.drawPath(path, paint);
} }
void drawHighArrow(Canvas canvas, Size size, Offset from, Offset to, void _drawHighArrow(Canvas canvas, Size size, Offset from, Offset to,
[bool doubleSided = false]) { [bool doubleSided = false]) {
Path path; Path path;
@ -150,7 +165,7 @@ class CurvePainter extends CustomPainter {
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round ..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round ..strokeJoin = StrokeJoin.round
..strokeWidth = lineWidth; ..strokeWidth = _lineWidth;
var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) +
(to.dy - from.dy) * (to.dy - from.dy)); (to.dy - from.dy) * (to.dy - from.dy));
@ -161,7 +176,7 @@ class CurvePainter extends CustomPainter {
path.relativeCubicTo( path.relativeCubicTo(
0, 0,
0, 0,
(from.dx + to.dx) / (length * 3) + 40, (from.dx + to.dx) / (length * 2) + 40,
(from.dy + to.dy) / (length * 2) + 40, (from.dy + to.dy) / (length * 2) + 40,
to.dx - from.dx, to.dx - from.dx,
to.dy - from.dy); to.dy - from.dy);
@ -173,29 +188,29 @@ class CurvePainter extends CustomPainter {
canvas.drawPath(path, paint); canvas.drawPath(path, paint);
} }
void drawConnections( void _drawConnections(
Canvas canvas, Size size, List<Dot> dots, Map<int, Offset> off) { Canvas canvas, Size size, List<Dot> dots, Map<int, Offset> off) {
for (var i in dots) { for (var i in dots) {
var list = i.getL(); var list = i.getL();
var beg = off[i.num]; var beg = off[i.num];
for (var d in list.keys) { for (var d in list.keys) {
if (d == i.num) { if (d == i.num) {
drawSelfConnect(canvas, off[d]!); _drawSelfConnect(canvas, off[d]!);
} else { } else {
if (graphData.getDoubleSidedBool()) { if (graphData.getDoubleSidedBool()) {
if (d > i.num) { if (d > i.num) {
drawHArrow(canvas, size, beg!, off[d]!, false); _drawHArrow(canvas, size, beg!, off[d]!, false);
if (graphData.getUseLengthBool()) { if (graphData.getUseLengthBool()) {
drawDotNames( _drawDotNames(
canvas, canvas,
Offset((off[d]!.dx + beg.dx) / 2 - 18, Offset((off[d]!.dx + beg.dx) / 2 - 18,
(off[d]!.dy + beg.dy) / 2 - 18), (off[d]!.dy + beg.dy) / 2 - 18),
i.getL()[d].toString()); i.getL()[d].toString());
} }
} else { } else {
drawHighArrow(canvas, size, beg!, off[d]!, false); _drawHighArrow(canvas, size, beg!, off[d]!, false);
if (graphData.getUseLengthBool()) { if (graphData.getUseLengthBool()) {
drawDotNames( _drawDotNames(
canvas, canvas,
Offset((off[d]!.dx + beg.dx) / 2 + 30, Offset((off[d]!.dx + beg.dx) / 2 + 30,
(off[d]!.dy + beg.dy) / 2 + 30), (off[d]!.dy + beg.dy) / 2 + 30),
@ -203,9 +218,9 @@ class CurvePainter extends CustomPainter {
} }
} }
} else { } else {
drawLine(canvas, beg!, off[d]!); _drawLine(canvas, beg!, off[d]!);
if (graphData.getUseLengthBool()) { if (graphData.getUseLengthBool()) {
drawDotNames( _drawDotNames(
canvas, canvas,
Offset((off[d]!.dx + beg.dx) / 2, (off[d]!.dy + beg.dy) / 2), Offset((off[d]!.dx + beg.dx) / 2, (off[d]!.dy + beg.dy) / 2),
i.getL()[d].toString()); i.getL()[d].toString());
@ -216,184 +231,67 @@ class CurvePainter extends CustomPainter {
} }
} }
void _drawBFS(Canvas canvas) {
if (bfsPath != null) {
for (int i = 0; i < bfsPath!.length; i++) {
_drawDot(canvas, _off[bfsPath![i]]!, 8, Colors.yellow);
}
_drawDot(canvas, _off[start]!, 9, Colors.green);
_drawDot(canvas, _off[end]!, 7, Colors.red.shade200);
for (int i = 0; i < bfsPath!.length; i++) {
_drawDotNum(canvas, _off[bfsPath![i]]!, "bfs: №${i + 1}");
}
}
}
void _drawDFS(Canvas canvas) {
if (dfsAccessTable != null) {
print("nn");
for (int i = 0; i < dfsAccessTable!.length; i++) {
if (dfsAccessTable![i]) {
_drawDot(canvas, _off[i + 1]!, 8, Colors.green.shade500);
_drawDotNum(canvas, _off[i + 1]!, "dfs: visible");
} else {
_drawDot(canvas, _off[i + 1]!, 7, Colors.red.shade500);
_drawDotNum(canvas, _off[i + 1]!, "dfs: not visible");
}
}
_drawDot(canvas, _off[start]!, 9, Colors.green.shade900);
}
}
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
if (size.width > size.height) { if (size.width > size.height) {
circleRad = size.height / 3; _circleRad = size.height / 3;
} else { } else {
circleRad = size.width / 3; _circleRad = size.width / 3;
} }
//var paint = Paint();
//drawLine(canvas, Offset(0, size.height / 2),
//Offset(size.width, size.height / 2));
//gr = getGraph(); _off = _getDotPos(graphData.getDotAmount(), size); //, higest);
//int higest = getHighConnections(); for (int i in _off.keys) {
//if (higest > -1) { _drawDot(canvas, _off[i]!);
var off = getDotPos(graphData.getDotAmount(), size); //, higest); //drawDotNames(canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]");
//off[higest] = Offset(size.width / 2, size.height / 2);
for (int i in off.keys) {
drawDot(canvas, off[i]!);
drawDotNames(
canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]");
} }
//var g = gr.getNoRepeatDots();
//print(g);
var g = graphData.getDots(); var g = graphData.getDots();
drawConnections(canvas, size, g, off); _drawBFS(canvas);
_drawDFS(canvas);
_drawConnections(canvas, size, g, _off);
//pringArr(canvas, size); //pringArr(canvas, size);
//drawArrow(canvas, Offset(size.width / 2, size.height / 2), //drawArrow(canvas, Offset(size.width / 2, size.height / 2),
// Offset(size.width / 2 + 50, size.height / 2 + 200)); // Offset(size.width / 2 + 50, size.height / 2 + 200));
//} //}
for (int i in _off.keys) {
//drawDot(canvas, off[i]!);
_drawDotNames(
canvas, _off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]");
}
} }
@override @override
bool shouldRepaint(CustomPainter oldDelegate) { bool shouldRepaint(CustomPainter oldDelegate) {
return true; return true;
} }
/*void _drawTextAt(String txt, Offset position, Canvas canvas) {
final textPainter = getTextPainter(txt);
textPainter.layout(minWidth: 0, maxWidth: 0);
Offset drawPosition =
Offset(position.dx, position.dy - (textPainter.height / 2));
textPainter.paint(canvas, drawPosition);
}*/
}
void pringArr(Canvas canvas, Size size) {
TextSpan textSpan;
TextPainter textPainter;
Path path;
// The arrows usually looks better with rounded caps.
Paint paint = Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = 3.0;
/// Draw a single arrow.
path = Path();
path.moveTo(size.width * 0.25, size.height * 0.10);
path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 0);
path = ArrowPath.make(path: path);
canvas.drawPath(path, paint..color = Colors.blue);
textSpan = const TextSpan(
text: 'Single arrow',
style: TextStyle(color: Colors.blue),
);
textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
textPainter.layout(minWidth: size.width);
textPainter.paint(canvas, Offset(0, size.height * 0.06));
/*
/// Draw a double sided arrow.
path = Path();
path.moveTo(size.width * 0.25, size.height * 0.2);
path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 0);
path = ArrowPath.make(path: path, isDoubleSided: true);
canvas.drawPath(path, paint..color = Colors.cyan);
textSpan = const TextSpan(
text: 'Double sided arrow',
style: TextStyle(color: Colors.cyan),
);
textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
textPainter.layout(minWidth: size.width);
textPainter.paint(canvas, Offset(0, size.height * 0.16));
/// Use complex path.
path = Path();
path.moveTo(size.width * 0.25, size.height * 0.3);
path.relativeCubicTo(0, 0, size.width * 0.25, 0, size.width * 0.5, 50);
path.relativeCubicTo(0, 0, -size.width * 0.25, 50, -size.width * 0.5, 50);
//path.relativeCubicTo(0, 0, size.width * 0.125, 10, size.width * 0.25, -10);
path = ArrowPath.make(path: path, isDoubleSided: true);
canvas.drawPath(path, paint..color = Colors.blue);
textSpan = const TextSpan(
text: 'Complex path',
style: TextStyle(color: Colors.blue),
);
textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
textPainter.layout(minWidth: size.width);
textPainter.paint(canvas, Offset(0, size.height * 0.28));
/// Draw several arrows on the same path.
path = Path();
path.moveTo(size.width * 0.25, size.height * 0.53);
path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 50);
path = ArrowPath.make(path: path);
path.relativeCubicTo(0, 0, -size.width * 0.25, 0, -size.width * 0.5, 50);
path = ArrowPath.make(path: path);
Path subPath = Path();
subPath.moveTo(size.width * 0.375, size.height * 0.53 + 100);
subPath.relativeCubicTo(0, 0, size.width * 0.125, 10, size.width * 0.25, -10);
subPath = ArrowPath.make(path: subPath, isDoubleSided: true);
path.addPath(subPath, Offset.zero);
canvas.drawPath(path, paint..color = Colors.cyan);
textSpan = const TextSpan(
text: 'Several arrows on the same path',
style: TextStyle(color: Colors.cyan),
);
textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
textPainter.layout(minWidth: size.width);
textPainter.paint(canvas, Offset(0, size.height * 0.49));
/// Adjusted
path = Path();
path.moveTo(size.width * 0.1, size.height * 0.8);
path.relativeCubicTo(0, 0, size.width * 0.3, 50, size.width * 0.25, 75);
path = ArrowPath.make(path: path, isAdjusted: true);
canvas.drawPath(path, paint..color = Colors.blue);
textSpan = const TextSpan(
text: 'Adjusted',
style: TextStyle(color: Colors.blue),
);
textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.left,
textDirection: TextDirection.ltr,
);
textPainter.layout();
textPainter.paint(canvas, Offset(size.width * 0.2, size.height * 0.77));
/// Non adjusted.
path = Path();
path.moveTo(size.width * 0.6, size.height * 0.8);
path.relativeCubicTo(0, 0, size.width * 0.3, 50, size.width * 0.25, 75);
path = ArrowPath.make(path: path, isAdjusted: false);
canvas.drawPath(path, paint..color = Colors.blue);
textSpan = const TextSpan(
text: 'Non adjusted',
style: TextStyle(color: Colors.blue),
);
textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.left,
textDirection: TextDirection.ltr,
);
textPainter.layout();
textPainter.paint(canvas, Offset(size.width * 0.65, size.height * 0.77));*/
} }

View File

@ -26,7 +26,10 @@ class _DrawingPageState extends State<DrawingPage> {
Graphs graphData = getGraph(); Graphs graphData = getGraph();
List<int>? bfsPath; List<int>? bfsPath;
List<bool>? dfsAccessTable; List<bool>? dfsAccessTable;
int? dfsStartDot; int? startDot;
int? endDot;
String? dropdownValue1;
String? dropdownValue2;
final _textNameController = TextEditingController(); final _textNameController = TextEditingController();
final _textNumbController = TextEditingController(); final _textNumbController = TextEditingController();
@ -34,118 +37,23 @@ class _DrawingPageState extends State<DrawingPage> {
final _textLnthController = TextEditingController(); final _textLnthController = TextEditingController();
final _textGrNmController = TextEditingController(); final _textGrNmController = TextEditingController();
void clearTextControllers() { void clearInputData() {
setState(() {
_textDestController.clear(); _textDestController.clear();
_textNumbController.clear(); _textNumbController.clear();
_textLnthController.clear(); _textLnthController.clear();
_textNameController.clear(); _textNameController.clear();
dropdownValue1 = null;
dropdownValue2 = null;
/*startDot = null;
bfsPath = null;
dfsAccessTable = null;
endDot = null;*/
});
} }
@override // *************buttons*************
Widget build(BuildContext context) { ElevatedButton createButton(String txt, void Function() onPressing) {
screenSize = MediaQuery.of(context).size.width;
_textGrNmController.text = graphData.getName();
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Align(
alignment: Alignment.topLeft,
child: Text("Graph name:\n",
style: TextStyle(
fontSize: 18,
color: Colors.white,
))),
toolbarHeight: 110,
flexibleSpace: Container(
color: Colors.green.shade900,
child: Column(children: <Widget>[
const SizedBox(height: 5),
Row(children: [
addSpaceW(screenSize / 8 + 19),
createButton("\nAdd dot\n", addDotPushed),
createInputBox("Dot name", screenSize / 4 - 25, Icons.label,
_textNameController),
addSpaceW(8),
createButton("\nAdd path\n", addPathPushed),
createInputBox("Input length", screenSize / 4 - 25,
Icons.arrow_right_alt_outlined, _textLnthController),
]),
addSpaceH(3),
Row(children: [
addSpaceW(5),
createInputBox(
"Name", screenSize / 8 - 25, null, _textGrNmController),
//addSpaceW(screenSize / 8 - 4),
createButton("\nDel dot \n", delDotPushed),
createInputBox("Dot number", screenSize / 4 - 25,
Icons.fiber_manual_record, _textNumbController),
addSpaceW(13),
createButton("\nDel path\n", delPathPushed),
createInputBox("Destination number", screenSize / 4 - 25,
Icons.fiber_manual_record, _textDestController),
]),
]),
),
actions: [
IconButton(
onPressed: () => graphData.flushData(),
icon: const Icon(Icons.delete_sweep),
iconSize: 60,
),
]),
body: CustomPaint(
painter: CurvePainter(
graphData: graphData,
bfsPath: bfsPath,
dfsStart: dfsStartDot,
dfsAccessTable: dfsAccessTable),
child: Align(
alignment: Alignment.topRight,
child: ButtonBar(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
createButton("Bfs", bfsPushed),
createButton("Dfs", dfsPushed),
createButton("Clear dfs or bfs", () => bfsPath = null),
createButton(graphData.getUseLengthStr(), changeLength),
createButton(graphData.getDoubleSidedStr(), changeOriented),
/*Text(_textGrNmController.text,
style:
TextStyle(fontSize: 15, color: Colors.blueGrey.shade900)),*/
createButton("Save to file", fileSaver),
createButton("Load from file", fileOpener),
createButton("Help", () {
String out =
" В поле \"Graph name\" можно сменить имя графу.\n";
out +=
" Для добавления точки необходимо ввести имя в \"Dot name\" и нажать на \"Add dot\".\n";
out +=
" Для удаления точки необходимо ввести номер в \"Dot number\" и нажать на \"Del dot\".\n";
out +=
" Для добавления пути необходимо ввести: номер выходной вершины в \"Dot number\", номер входной вершины в \"Destination number\" ";
out +=
"и, если граф взвешенный, то ввести длину пути в \"Input length\". Затем нажать \"Add path\".\n";
out +=
" Для удаления пути необходимо ввести номер выходной вершины в \"Dot number\" и номер входной вершины в \"Destination number\". Затем нажать \"Del path\".\n\n";
out +=
" Кнопки \"Bfs\" и \"Dfs\" нумеруют точки в зависимости от послежовательности, в которой они будут пройдены.\n";
out +=
" Кнопки \"Взвешенный\" и \"Ориентированный\" позволяют сменить эти значения перед построением графа (т.е. для их работы граф должен быть пустым).\n";
out +=
" Кнопки \"Save to file\" и \"Load from file\" позволяют вывести информацию в файл и загрузить информацию из файла соответственно.\n";
out +=
" Кнопка \"Help\" описывает работу с интерфейсом программы.";
showPopUp("Help:", out);
})
],
),
),
),
));
}
// ignore: avoid_types_as_parameter_names, non_constant_identifier_names, use_function_type_syntax_for_parameters
ElevatedButton createButton(String txt, void onPressing()) {
return ElevatedButton( return ElevatedButton(
onPressed: onPressing, onPressed: onPressing,
style: ButtonStyle( style: ButtonStyle(
@ -160,6 +68,32 @@ class _DrawingPageState extends State<DrawingPage> {
); );
} }
void showPopUp(String alertTitle, String err) => showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text(alertTitle),
content: Text(err),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
),
],
),
);
// *************buttons*************
// ***addSpace***
SizedBox addSpaceH(double h) {
return SizedBox(height: h);
}
SizedBox addSpaceW(double w) {
return SizedBox(width: w);
}
// ***addSpace***
// *************inputs*************
Container createInputBox(String text, double wid, IconData? icon, Container createInputBox(String text, double wid, IconData? icon,
TextEditingController? controller) { TextEditingController? controller) {
if (icon == null) { if (icon == null) {
@ -203,32 +137,78 @@ class _DrawingPageState extends State<DrawingPage> {
)); ));
} }
SizedBox addSpaceH(double h) { SizedBox dropList1(double width) {
return SizedBox(height: h); var button = DropdownButton(
} hint: const Text(
'Select Dot',
SizedBox addSpaceW(double w) { style: TextStyle(color: Colors.white, fontSize: 13),
return SizedBox(width: w);
}
void showPopUp(String alertTitle, String err) => showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text(alertTitle),
content: Text(err),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'OK'),
child: const Text('OK'),
), ),
], //icon: const Icon(Icons.fiber_manual_record, color: Colors.white),
alignment: AlignmentDirectional.bottomEnd,
value: dropdownValue1,
isDense: true,
borderRadius: const BorderRadius.all(Radius.circular(20)),
dropdownColor: Colors.green.shade800,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
), ),
onChanged: (String? newValue) {
setState(() {
dropdownValue1 = newValue;
});
},
items: graphData.getDots().map((location) {
return DropdownMenuItem(
child: Text(location.getName()),
value: location.num.toString(),
); );
}).toList(),
);
return SizedBox(
child: button,
width: width,
);
}
SizedBox dropList2(double width) {
var button = DropdownButton(
hint: const Text(
'Select Dot',
style: TextStyle(color: Colors.white, fontSize: 13),
),
alignment: AlignmentDirectional.centerEnd,
value: dropdownValue2,
isDense: true,
borderRadius: const BorderRadius.all(Radius.circular(20)),
dropdownColor: Colors.green.shade800,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
),
onChanged: (String? newValue) {
setState(() {
dropdownValue2 = newValue;
});
},
items: graphData.getDots().map((location) {
return DropdownMenuItem(
child: Text(location.getName()),
value: location.num.toString(),
);
}).toList(),
);
return SizedBox(
child: button,
width: width,
);
}
// *************inputs*************
//*********ButtonsFunctions********* //*********ButtonsFunctions*********
void addDotPushed() { void addDotPushed() {
//showPopUp("Test", "Test message");
//var inp = int.tryParse(_textNameController.text);
setState(() { setState(() {
if (_textNameController.text == "") { if (_textNameController.text == "") {
showPopUp("Error", "No name in \"Dot name\" box"); showPopUp("Error", "No name in \"Dot name\" box");
@ -238,26 +218,24 @@ class _DrawingPageState extends State<DrawingPage> {
showPopUp("Error", res); showPopUp("Error", res);
} }
} }
clearTextControllers(); clearInputData();
}); });
} }
void addPathPushed() { void addPathPushed() {
setState(() { setState(() {
if (_textNumbController.text == "") { if (dropdownValue1 == null) {
showPopUp("Error", "No number in \"Dot number\" box"); showPopUp("Error", "Select output dot");
} else if (_textDestController.text == "") { } else if (dropdownValue2 == null) {
showPopUp("Error", "No number in \"Destination number\" box"); showPopUp("Error", "select input dot");
} else if (_textLnthController.text == "" && } else if (_textLnthController.text == "" &&
graphData.getUseLengthBool()) { graphData.getUseLengthBool()) {
showPopUp("Error", "No length in \"Input length\" box"); showPopUp("Error", "No length in \"Input length\" box");
} else { } else {
int? from = int.tryParse(_textNumbController.text); int? from = int.parse(dropdownValue1!);
int? to = int.tryParse(_textDestController.text); int? to = int.parse(dropdownValue2!);
int? len = int.tryParse(_textLnthController.text); int? len = int.tryParse(_textLnthController.text);
if (from == null || if (len == null && graphData.getUseLengthBool()) {
to == null ||
(len == null && graphData.getUseLengthBool())) {
showPopUp("Error", showPopUp("Error",
"Can't parse input.\nInts only allowed in \"Dot number\", \"Destination number\" and \"Input length\""); "Can't parse input.\nInts only allowed in \"Dot number\", \"Destination number\" and \"Input length\"");
} else { } else {
@ -268,7 +246,7 @@ class _DrawingPageState extends State<DrawingPage> {
} }
} }
} }
clearTextControllers(); clearInputData();
}); });
} }
@ -305,26 +283,18 @@ class _DrawingPageState extends State<DrawingPage> {
} }
} }
} }
clearTextControllers(); clearInputData();
}); });
} }
void delDotPushed() { void delDotPushed() {
setState(() { setState(() {
if (_textNumbController.text == "") { if (dropdownValue1 != null) {
showPopUp("Error", "No number in \"Dot number\" box"); graphData.delDot(int.parse(dropdownValue1!));
} else { } else {
int? dot = int.tryParse(_textNumbController.text); showPopUp("Error", "Nothing in input");
if (dot == null) {
showPopUp("Error", "Can't parse input.\nInts only allowed");
} else {
String? res = graphData.delDot(dot);
if (res != null) {
showPopUp("Error", res);
} }
} clearInputData();
}
clearTextControllers();
}); });
} }
@ -336,14 +306,12 @@ class _DrawingPageState extends State<DrawingPage> {
if (!result.files.single.path!.endsWith(".txt")) { if (!result.files.single.path!.endsWith(".txt")) {
showPopUp("Error", "Can open only \".txt\" files"); showPopUp("Error", "Can open only \".txt\" files");
} else { } else {
//print(result.files.single.path!);
String? res = String? res =
graphData.replaceDataFromFile(result.files.single.path!); graphData.replaceDataFromFile(result.files.single.path!);
if (res != null) showPopUp("Error", res); if (res != null) showPopUp("Error", res);
} }
} else { } else {
showPopUp("Error", "No file selected"); showPopUp("Error", "No file selected");
// User canceled the picker
} }
}); });
} }
@ -355,7 +323,6 @@ class _DrawingPageState extends State<DrawingPage> {
allowedExtensions: ["txt"]); allowedExtensions: ["txt"]);
if (outputFile == null) { if (outputFile == null) {
showPopUp("Error", "Save cancelled"); showPopUp("Error", "Save cancelled");
// User canceled the picker
} else { } else {
if (!outputFile.endsWith(".txt")) { if (!outputFile.endsWith(".txt")) {
outputFile += ".txt"; outputFile += ".txt";
@ -366,51 +333,167 @@ class _DrawingPageState extends State<DrawingPage> {
void bfsPushed() { void bfsPushed() {
setState(() { setState(() {
dfsAccessTable = null;
bfsPath = null; bfsPath = null;
if (_textNumbController.text == "") { dfsAccessTable = null;
startDot = null;
endDot = null;
if (dropdownValue1 == null) {
showPopUp("Error", "No number in \"Dot number\" box"); showPopUp("Error", "No number in \"Dot number\" box");
} else if (_textDestController.text == "") { } else if (dropdownValue2 == null) {
showPopUp("Error", "No number in \"Destination number\" box"); showPopUp("Error", "No number in \"Destination number\" box");
} else { } else {
int? from = int.tryParse(_textNumbController.text); startDot = int.parse(dropdownValue1!);
int? to = int.tryParse(_textDestController.text); endDot = int.parse(dropdownValue2!);
if (from == null || to == null) {
showPopUp("Error", bfsPath = graphData.bfsPath(startDot!, endDot!);
"Can't parse input.\nInts only allowed in \"Dot number\" and \"Destination number\"");
} else {
bfsPath = graphData.bfsPath(from, to);
if (bfsPath == null) { if (bfsPath == null) {
showPopUp("Info", "There is no path"); showPopUp("Info", "There is no path");
} }
print(bfsPath); print(bfsPath);
} }
}
clearTextControllers();
}); });
clearInputData();
} }
void dfsPushed() { void dfsPushed() {
setState(() { setState(() {
bfsPath = null; bfsPath = null;
bfsPath = null; dfsAccessTable = null;
if (_textNumbController.text == "") { startDot = null;
endDot = null;
if (dropdownValue1 == null) {
showPopUp("Error", "No number in \"Dot number\" box"); showPopUp("Error", "No number in \"Dot number\" box");
} else { } else {
int? from = int.tryParse(_textNumbController.text); startDot = int.parse(dropdownValue1!);
if (from == null) { dfsAccessTable = graphData.dfsIterative(startDot!);
showPopUp("Error",
"Can't parse input.\nInts only allowed in \"Dot number\".");
} else {
dfsAccessTable = graphData.dfsIterative(from);
if (dfsAccessTable == null) { if (dfsAccessTable == null) {
showPopUp("Err", "report this error."); showPopUp("Err", "report this error.");
} }
print(dfsAccessTable); print(dfsAccessTable);
} }
} clearInputData();
clearTextControllers();
}); });
} }
//*********ButtonsFunctions********* //*********ButtonsFunctions*********
// build
@override
Widget build(BuildContext context) {
screenSize = MediaQuery.of(context).size.width;
_textGrNmController.text = graphData.getName();
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Align(
alignment: Alignment.topLeft,
child: Text("Graph name:\n",
style: TextStyle(
fontSize: 18,
color: Colors.white,
))),
toolbarHeight: 110,
flexibleSpace: Container(
color: Colors.green.shade900,
child: Column(children: <Widget>[
const SizedBox(height: 5),
Row(children: [
addSpaceW(screenSize / 8 + 19),
createButton("\nAdd dot\n", addDotPushed),
createInputBox("Dot name", screenSize / 4 - 25, Icons.label,
_textNameController),
addSpaceW(8),
createButton("\nAdd path\n", addPathPushed),
createInputBox("Input length", screenSize / 4 - 25,
Icons.arrow_right_alt_outlined, _textLnthController),
]),
addSpaceH(3),
Row(children: [
addSpaceW(6),
createInputBox(
"Name", screenSize / 8 - 25, null, _textGrNmController),
//addSpaceW(screenSize / 8 - 4),
createButton("\nDel dot \n", delDotPushed),
//createInputBox("Dot number", screenSize / 4 - 25, Icons.fiber_manual_record, _textNumbController),
addSpaceW(54),
dropList1(screenSize / 4 - 80),
addSpaceW(54),
createButton("\nDel path\n", delPathPushed),
addSpaceW(54),
dropList2(screenSize / 4 - 80),
//createInputBox("Destination number", screenSize / 4 - 25, Icons.fiber_manual_record, _textDestController),
]),
]),
),
actions: [
IconButton(
onPressed: () {
setState(() {
startDot = null;
endDot = null;
bfsPath = null;
dfsAccessTable = null;
graphData.flushData();
clearInputData();
});
},
icon: const Icon(Icons.delete_sweep),
iconSize: 60,
),
]),
body: CustomPaint(
painter: CurvePainter(
graphData: graphData,
bfsPath: bfsPath,
dfsAccessTable: dfsAccessTable,
start: startDot,
end: endDot),
child: Align(
alignment: Alignment.topRight,
child: ButtonBar(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
createButton("Bfs", bfsPushed),
createButton("Dfs", dfsPushed),
createButton("Clear dfs or bfs", () {
setState(() {
bfsPath = null;
dfsAccessTable = null;
startDot = null;
endDot = null;
clearInputData();
});
}),
createButton(graphData.getUseLengthStr(), changeLength),
createButton(graphData.getDoubleSidedStr(), changeOriented),
createButton("Save to file", fileSaver),
createButton("Load from file", fileOpener),
createButton("Help", () {
String out =
" В поле \"Graph name\" можно сменить имя графу.\n";
out +=
" Для добавления точки необходимо ввести имя в \"Dot name\" и нажать на \"Add dot\".\n";
out +=
" Для удаления точки необходимо ввести номер в \"Dot number\" и нажать на \"Del dot\".\n";
out +=
" Для добавления пути необходимо ввести: номер выходной вершины в \"Dot number\", номер входной вершины в \"Destination number\" ";
out +=
"и, если граф взвешенный, то ввести длину пути в \"Input length\". Затем нажать \"Add path\".\n";
out +=
" Для удаления пути необходимо ввести номер выходной вершины в \"Dot number\" и номер входной вершины в \"Destination number\". Затем нажать \"Del path\".\n\n";
out +=
" Кнопки \"Bfs\" и \"Dfs\" нумеруют точки в зависимости от послежовательности, в которой они будут пройдены.\n";
out +=
" Кнопки \"Взвешенный\" и \"Ориентированный\" позволяют сменить эти значения перед построением графа (т.е. для их работы граф должен быть пустым).\n";
out +=
" Кнопки \"Save to file\" и \"Load from file\" позволяют вывести информацию в файл и загрузить информацию из файла соответственно.\n";
out +=
" Кнопка \"Help\" описывает работу с интерфейсом программы.";
showPopUp("Help:", out);
})
],
),
),
),
));
}
} }

View File

@ -363,6 +363,7 @@ class Graphs {
List<Dot> getDots() => _dots; List<Dot> getDots() => _dots;
String getName() => _name; String getName() => _name;
String? getNameByNum(int n) => _nameTable[n]; String? getNameByNum(int n) => _nameTable[n];
Map<int, String> getNameTable() => _nameTable;
int getDotAmount() => _dots.length; int getDotAmount() => _dots.length;
int? getNumByName(String n) { int? getNumByName(String n) {
for (var i in _nameTable.keys) { for (var i in _nameTable.keys) {
@ -567,6 +568,7 @@ class Graphs {
}*/ }*/
List<int>? bfsPath(int startDot, int goalDot) { List<int>? bfsPath(int startDot, int goalDot) {
if (startDot == goalDot) return [startDot];
//if (!bfsHasPath(startDot, goalDot)) return null; //if (!bfsHasPath(startDot, goalDot)) return null;
startDot--; startDot--;
goalDot--; goalDot--;
@ -606,7 +608,6 @@ class Graphs {
//Восстановим кратчайший путь //Восстановим кратчайший путь
//Для восстановления пути пройдём его в обратном порядке, и развернём. //Для восстановления пути пройдём его в обратном порядке, и развернём.
List<int> path = <int>[]; List<int> path = <int>[];
int cur = goalDot; //текущая вершина пути int cur = goalDot; //текущая вершина пути