Exemplo n.º 1
0
        private List <QueueItemMatrix> GetAdjucentCell(int[,] matrix, QueueItemMatrix cell, bool[,] visisted, int lenX, int lenY)
        {
            var list = new List <QueueItemMatrix>();

            for (int i = 0; i < 4; i++)
            {
                var newX = cell.Cell.x + dirX[i];
                var newY = cell.Cell.y + dirY[i];

                if (newX < 0 || newY < 0 || newX >= lenX || newY >= lenY)
                {
                    continue;
                }

                if (visisted[newX, newY])
                {
                    continue;
                }

                if (matrix[newX, newY] == -1)
                {
                    continue;
                }

                list.Add(new QueueItemMatrix(new MatrixCell(newX, newY), cell.Level + 1));
            }
            return(list);
        }
Exemplo n.º 2
0
        public void PathBFS(int[,] matrix)
        {
            var lenX = matrix.GetLength(0);
            var lenY = matrix.GetLength(1);

            var visited = new bool[lenX, lenY];
            Queue <QueueItemMatrix> queue = new Queue <QueueItemMatrix>();
            var path = new List <PathItem>();

            var startQueueItem = new QueueItemMatrix(new MatrixCell(0, 0), 0);

            queue.Enqueue(startQueueItem);

            path.Add(new PathItem(startQueueItem.Cell, null));

            MatrixCell destinationCell = null;

            while (queue.Any())
            {
                var cell = queue.Dequeue();

                visited[cell.Cell.x, cell.Cell.y] = true;

                if (matrix[cell.Cell.x, cell.Cell.y] == 0)
                {
                    destinationCell = cell.Cell;
                    break;
                }

                var list = GetAdjucentCell(matrix, cell, visited, lenX, lenY);
                foreach (var item in list)
                {
                    path.Add(new PathItem(item.Cell, cell.Cell));
                    queue.Enqueue(item);
                }
            }

            if (destinationCell != null)
            {
                reconstructPath(destinationCell, path);
            }
            else
            {
                Console.WriteLine("No Path found");
            }
        }