Exemple #1
0
        private BFSInfo CalculateBFSInfo(int x, int y, int[][] grid)
        {
            BFSInfo result = new BFSInfo();

            bool[,] selected = new bool[grid.Length, grid[0].Length];

            LinkedList <int[]> queue = new LinkedList <int[]>();

            queue.AddLast(new int[] { x, y, 0 });

            while (queue.Count != 0)
            {
                var value = queue.First.Value;
                queue.RemoveFirst();

                if (value[0] == grid.Length - 1 && value[1] == grid[0].Length - 1)
                {
                    result.Result = value[2];
                    var lessValue = value[2] - 1;
                    while (result.Obstacles.Count != 0)
                    {
                        if (result.Obstacles.Last.Value[2] >= lessValue)
                        {
                            result.Obstacles.RemoveLast();
                        }
                        else
                        {
                            break;
                        }
                    }
                    break;
                }
                IEnumerable <int[]> nextPositions = GetNextPositions(value, grid);
                var nextValue = value[2] + 1;
                foreach (var item in nextPositions.Where(e => !selected[e[0], e[1]]))
                {
                    if (grid[item[0]][item[1]] == 1)
                    {
                        result.Obstacles.AddLast(new int[] { item[0], item[1], nextValue });
                    }
                    else
                    {
                        queue.AddLast(new int[] { item[0], item[1], nextValue });
                    }
                    selected[item[0], item[1]] = true;
                }
            }

            return(result);
        }
Exemple #2
0
        public int ShortestPath(int[][] grid, int k)
        {
            if (k >= grid.Length + grid[0].Length - 3)
            {
                return(grid.Length + grid[0].Length - 2);
            }

            BFSInfo[,] infos    = new BFSInfo[grid.Length, grid[0].Length];
            int?[,,]  solutions = new int?[grid.Length, grid[0].Length, k + 1];
            for (int i = 0; i <= k; i++)
            {
                solutions[grid.Length - 1, grid[0].Length - 1, i] = 0;
            }

            return(ShortestPath(0, 0, k, grid, infos, solutions));
        }