Compare commits

...

16 Commits

Author SHA1 Message Date
Морозов Андрей 9024c24c4c Merge remote-tracking branch 'Graphs_dart/bfs&dfs' 2021-11-10 19:48:00 +04:00
Морозов Андрей 49ce4aa12f Загрузил(а) файлы в 'flutter/lib/pages' 2021-11-10 12:28:58 +00:00
Морозов Андрей daddfeed6f Загрузил(а) файлы в 'flutter/lib/src' 2021-11-10 12:28:38 +00:00
Морозов Андрей 0a0698bd01 Загрузил(а) файлы в 'flutter/lib' 2021-11-10 12:28:24 +00:00
Морозов Андрей 749afe3e6e option for bfs 2021-11-10 12:26:46 +00:00
Морозов Андрей 442288141d function reordering 2021-11-10 12:05:16 +00:00
Морозов Андрей 4b3542edad src from flutter 2021-11-10 12:04:06 +00:00
Морозов Андрей 77c2f02a96 src from flutter 2021-11-10 12:03:49 +00:00
Морозов Андрей f20cb1fef0 fix null check 2021-11-10 11:37:25 +00:00
Морозов Андрей 41de1ba314 Загрузил(а) файлы в 'flutter/lib/src' 2021-11-10 11:26:41 +00:00
Морозов Андрей 276e7d36ed Загрузил(а) файлы в 'flutter/lib/pages' 2021-11-10 11:26:25 +00:00
Морозов Андрей 3950fabb86 Загрузил(а) файлы в 'flutter/lib' 2021-11-10 11:26:10 +00:00
Морозов Андрей 7bbb414212 Удалить 'flutter/lib/graph.dart' 2021-11-10 11:25:57 +00:00
Морозов Андрей 364495be65 Удалить 'flutter/lib/drawing_page.dart' 2021-11-10 11:25:47 +00:00
Морозов Андрей 3e0be6b7db Удалить 'flutter/lib/curve_painter.dart' 2021-11-10 11:25:17 +00:00
Морозов Андрей a83c683e72 Загрузил(а) файлы в 'flutter/lib' 2021-11-10 11:24:31 +00:00
5 changed files with 604 additions and 459 deletions

View File

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

View File

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

View File

@ -8,71 +8,85 @@ class CurvePainter extends CustomPainter {
Key? key,
required this.graphData,
required this.bfsPath,
required this.dfsStart,
required this.start,
required this.end,
required this.dfsAccessTable,
});
List<int>? bfsPath;
List<bool>? dfsAccessTable;
int? dfsStart;
int? start;
int? end;
Graphs graphData;
final double dotRad = 6;
final double lineWidth = 2;
final Color lineColor = Colors.black;
final double aboveHeight = 5;
double circleRad = 100;
final TextStyle textStyle = TextStyle(
color: Colors.green.shade900,
final double _dotRad = 6;
final double _lineWidth = 1.5;
final Color _lineColor = Colors.black;
final double _aboveHeight = 5;
double _circleRad = 100;
final TextStyle _textStyle = TextStyle(
color: Colors.red.shade900,
decorationColor: Colors.green.shade900,
decorationThickness: 10,
decorationStyle: TextDecorationStyle.dashed,
fontSize: 20,
);
void drawLine(Canvas canvas, Offset p1, Offset p2) {
Map<int, Offset> _off = <int, Offset>{};
void _drawLine(Canvas canvas, Offset p1, Offset p2) {
Paint p = Paint();
p.color = lineColor;
p.strokeWidth = lineWidth;
p.color = _lineColor;
p.strokeWidth = _lineWidth;
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();
p.color = Colors.yellow.shade900;
p.strokeWidth = lineWidth + 2;
canvas.drawCircle(p1, dotRad, p);
p.color = col;
p.strokeWidth = _lineWidth + 2;
canvas.drawCircle(p1, _dotRad + plusRad, p);
}
void drawSelfConnect(Canvas canvas, Offset p1) {
void _drawSelfConnect(Canvas canvas, Offset p1) {
var p = Paint();
p.color = lineColor;
p.strokeWidth = lineWidth;
p.color = _lineColor;
p.strokeWidth = _lineWidth;
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(
text: _getTextSpan(s),
textDirection: TextDirection.ltr,
textAlign: TextAlign.center);
void drawDotNames(Canvas canvas, Offset place, String s) {
void _drawDotNames(Canvas canvas, Offset place, String s) {
var textPainter = _getTextPainter(s);
textPainter.layout();
textPainter.paint(
canvas,
Offset((place.dx - textPainter.width),
(place.dy - textPainter.height) - aboveHeight));
(place.dy - textPainter.height) - _aboveHeight));
}
void drawAboveText(Canvas canvas, Offset size, String s) {
var textPainter = _getTextPainter(s);
void _drawDotNum(Canvas canvas, Offset size, String 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.paint(
canvas,
Offset((size.dx - textPainter.width),
(size.dy - textPainter.height) - aboveHeight));
Offset((size.dx - textPainter.width) + 25,
(size.dy - textPainter.height) + _aboveHeight + 30));
}
int getHighInputConnections() {
int _getHighInputConnections() {
if (graphData.getDots().length != 1 && graphData.getDots().length <= 3) {
return -1;
}
@ -83,17 +97,18 @@ class CurvePainter extends CustomPainter {
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>{};
var width = size.width / 2;
var height = size.height / 2;
int add = 0;
int h = getHighInputConnections();
int h = _getHighInputConnections();
for (int i = 0; i < dotsAm; i++) {
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 =
sin(2 * pi * (i - add) / (dotsAm - add)) * circleRad + height;
sin(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + height;
off[i + 1] = Offset(x, y);
} else if ((i + 1) == h) {
@ -110,7 +125,7 @@ class CurvePainter extends CustomPainter {
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]) {
Path path;
@ -120,7 +135,7 @@ class CurvePainter extends CustomPainter {
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = lineWidth;
..strokeWidth = _lineWidth;
var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) +
(to.dy - from.dy) * (to.dy - from.dy));
@ -131,8 +146,8 @@ class CurvePainter extends CustomPainter {
path.relativeCubicTo(
0,
0,
-(from.dx + to.dx) / (length * 2) - 40,
-(from.dy + to.dy) / (length * 2) - 40,
-(from.dx + to.dx + length) / (length) - 40,
-(from.dy + to.dy + length) / (length) - 40,
to.dx - from.dx,
to.dy - from.dy);
path =
@ -140,7 +155,7 @@ class CurvePainter extends CustomPainter {
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]) {
Path path;
@ -150,7 +165,7 @@ class CurvePainter extends CustomPainter {
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = lineWidth;
..strokeWidth = _lineWidth;
var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) +
(to.dy - from.dy) * (to.dy - from.dy));
@ -161,7 +176,7 @@ class CurvePainter extends CustomPainter {
path.relativeCubicTo(
0,
0,
(from.dx + to.dx) / (length * 3) + 40,
(from.dx + to.dx) / (length * 2) + 40,
(from.dy + to.dy) / (length * 2) + 40,
to.dx - from.dx,
to.dy - from.dy);
@ -173,29 +188,29 @@ class CurvePainter extends CustomPainter {
canvas.drawPath(path, paint);
}
void drawConnections(
void _drawConnections(
Canvas canvas, Size size, List<Dot> dots, Map<int, Offset> off) {
for (var i in dots) {
var list = i.getL();
var beg = off[i.num];
for (var d in list.keys) {
if (d == i.num) {
drawSelfConnect(canvas, off[d]!);
_drawSelfConnect(canvas, off[d]!);
} else {
if (graphData.getDoubleSidedBool()) {
if (d > i.num) {
drawHArrow(canvas, size, beg!, off[d]!, false);
_drawHArrow(canvas, size, beg!, off[d]!, false);
if (graphData.getUseLengthBool()) {
drawDotNames(
_drawDotNames(
canvas,
Offset((off[d]!.dx + beg.dx) / 2 - 18,
(off[d]!.dy + beg.dy) / 2 - 18),
i.getL()[d].toString());
}
} else {
drawHighArrow(canvas, size, beg!, off[d]!, false);
_drawHighArrow(canvas, size, beg!, off[d]!, false);
if (graphData.getUseLengthBool()) {
drawDotNames(
_drawDotNames(
canvas,
Offset((off[d]!.dx + beg.dx) / 2 + 30,
(off[d]!.dy + beg.dy) / 2 + 30),
@ -203,9 +218,9 @@ class CurvePainter extends CustomPainter {
}
}
} else {
drawLine(canvas, beg!, off[d]!);
_drawLine(canvas, beg!, off[d]!);
if (graphData.getUseLengthBool()) {
drawDotNames(
_drawDotNames(
canvas,
Offset((off[d]!.dx + beg.dx) / 2, (off[d]!.dy + beg.dy) / 2),
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
void paint(Canvas canvas, Size size) {
if (size.width > size.height) {
circleRad = size.height / 3;
_circleRad = size.height / 3;
} 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();
//int higest = getHighConnections();
//if (higest > -1) {
var off = getDotPos(graphData.getDotAmount(), size); //, higest);
//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]");
_off = _getDotPos(graphData.getDotAmount(), size); //, higest);
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();
drawConnections(canvas, size, g, off);
_drawBFS(canvas);
_drawDFS(canvas);
_drawConnections(canvas, size, g, _off);
//pringArr(canvas, size);
//drawArrow(canvas, Offset(size.width / 2, size.height / 2),
// 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
bool shouldRepaint(CustomPainter oldDelegate) {
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();
List<int>? bfsPath;
List<bool>? dfsAccessTable;
int? dfsStartDot;
int? startDot;
int? endDot;
String? dropdownValue1;
String? dropdownValue2;
final _textNameController = TextEditingController();
final _textNumbController = TextEditingController();
@ -34,118 +37,23 @@ class _DrawingPageState extends State<DrawingPage> {
final _textLnthController = TextEditingController();
final _textGrNmController = TextEditingController();
void clearTextControllers() {
void clearInputData() {
setState(() {
_textDestController.clear();
_textNumbController.clear();
_textLnthController.clear();
_textNameController.clear();
dropdownValue1 = null;
dropdownValue2 = null;
/*startDot = null;
bfsPath = null;
dfsAccessTable = null;
endDot = null;*/
});
}
@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(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()) {
// *************buttons*************
ElevatedButton createButton(String txt, void Function() onPressing) {
return ElevatedButton(
onPressed: onPressing,
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,
TextEditingController? controller) {
if (icon == null) {
@ -203,32 +137,78 @@ class _DrawingPageState extends State<DrawingPage> {
));
}
SizedBox addSpaceH(double h) {
return SizedBox(height: h);
}
SizedBox addSpaceW(double w) {
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'),
SizedBox dropList1(double width) {
var button = DropdownButton(
hint: const Text(
'Select Dot',
style: TextStyle(color: Colors.white, fontSize: 13),
),
],
//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*********
void addDotPushed() {
//showPopUp("Test", "Test message");
//var inp = int.tryParse(_textNameController.text);
setState(() {
if (_textNameController.text == "") {
showPopUp("Error", "No name in \"Dot name\" box");
@ -238,26 +218,24 @@ class _DrawingPageState extends State<DrawingPage> {
showPopUp("Error", res);
}
}
clearTextControllers();
clearInputData();
});
}
void addPathPushed() {
setState(() {
if (_textNumbController.text == "") {
showPopUp("Error", "No number in \"Dot number\" box");
} else if (_textDestController.text == "") {
showPopUp("Error", "No number in \"Destination number\" box");
if (dropdownValue1 == null) {
showPopUp("Error", "Select output dot");
} else if (dropdownValue2 == null) {
showPopUp("Error", "select input dot");
} else if (_textLnthController.text == "" &&
graphData.getUseLengthBool()) {
showPopUp("Error", "No length in \"Input length\" box");
} else {
int? from = int.tryParse(_textNumbController.text);
int? to = int.tryParse(_textDestController.text);
int? from = int.parse(dropdownValue1!);
int? to = int.parse(dropdownValue2!);
int? len = int.tryParse(_textLnthController.text);
if (from == null ||
to == null ||
(len == null && graphData.getUseLengthBool())) {
if (len == null && graphData.getUseLengthBool()) {
showPopUp("Error",
"Can't parse input.\nInts only allowed in \"Dot number\", \"Destination number\" and \"Input length\"");
} 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() {
setState(() {
if (_textNumbController.text == "") {
showPopUp("Error", "No number in \"Dot number\" box");
if (dropdownValue1 != null) {
graphData.delDot(int.parse(dropdownValue1!));
} else {
int? dot = int.tryParse(_textNumbController.text);
if (dot == null) {
showPopUp("Error", "Can't parse input.\nInts only allowed");
} else {
String? res = graphData.delDot(dot);
if (res != null) {
showPopUp("Error", res);
showPopUp("Error", "Nothing in input");
}
}
}
clearTextControllers();
clearInputData();
});
}
@ -336,14 +306,12 @@ class _DrawingPageState extends State<DrawingPage> {
if (!result.files.single.path!.endsWith(".txt")) {
showPopUp("Error", "Can open only \".txt\" files");
} else {
//print(result.files.single.path!);
String? res =
graphData.replaceDataFromFile(result.files.single.path!);
if (res != null) showPopUp("Error", res);
}
} else {
showPopUp("Error", "No file selected");
// User canceled the picker
}
});
}
@ -355,7 +323,6 @@ class _DrawingPageState extends State<DrawingPage> {
allowedExtensions: ["txt"]);
if (outputFile == null) {
showPopUp("Error", "Save cancelled");
// User canceled the picker
} else {
if (!outputFile.endsWith(".txt")) {
outputFile += ".txt";
@ -366,51 +333,167 @@ class _DrawingPageState extends State<DrawingPage> {
void bfsPushed() {
setState(() {
dfsAccessTable = null;
bfsPath = null;
if (_textNumbController.text == "") {
dfsAccessTable = null;
startDot = null;
endDot = null;
if (dropdownValue1 == null) {
showPopUp("Error", "No number in \"Dot number\" box");
} else if (_textDestController.text == "") {
} else if (dropdownValue2 == null) {
showPopUp("Error", "No number in \"Destination number\" box");
} else {
int? from = int.tryParse(_textNumbController.text);
int? to = int.tryParse(_textDestController.text);
if (from == null || to == null) {
showPopUp("Error",
"Can't parse input.\nInts only allowed in \"Dot number\" and \"Destination number\"");
} else {
bfsPath = graphData.bfsPath(from, to);
startDot = int.parse(dropdownValue1!);
endDot = int.parse(dropdownValue2!);
bfsPath = graphData.bfsPath(startDot!, endDot!);
if (bfsPath == null) {
showPopUp("Info", "There is no path");
}
print(bfsPath);
}
}
clearTextControllers();
});
clearInputData();
}
void dfsPushed() {
setState(() {
bfsPath = null;
bfsPath = null;
if (_textNumbController.text == "") {
dfsAccessTable = null;
startDot = null;
endDot = null;
if (dropdownValue1 == null) {
showPopUp("Error", "No number in \"Dot number\" box");
} else {
int? from = int.tryParse(_textNumbController.text);
if (from == null) {
showPopUp("Error",
"Can't parse input.\nInts only allowed in \"Dot number\".");
} else {
dfsAccessTable = graphData.dfsIterative(from);
startDot = int.parse(dropdownValue1!);
dfsAccessTable = graphData.dfsIterative(startDot!);
if (dfsAccessTable == null) {
showPopUp("Err", "report this error.");
}
print(dfsAccessTable);
}
}
clearTextControllers();
clearInputData();
});
}
//*********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;
String getName() => _name;
String? getNameByNum(int n) => _nameTable[n];
Map<int, String> getNameTable() => _nameTable;
int getDotAmount() => _dots.length;
int? getNumByName(String n) {
for (var i in _nameTable.keys) {
@ -567,6 +568,7 @@ class Graphs {
}*/
List<int>? bfsPath(int startDot, int goalDot) {
if (startDot == goalDot) return [startDot];
//if (!bfsHasPath(startDot, goalDot)) return null;
startDot--;
goalDot--;
@ -606,7 +608,6 @@ class Graphs {
//Восстановим кратчайший путь
//Для восстановления пути пройдём его в обратном порядке, и развернём.
List<int> path = <int>[];
int cur = goalDot; //текущая вершина пути