Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace _8.DistanceInLabyrinth
- {
- using System;
- using System.Collections.Generic;
- public class DistanceInLabyrinthMain
- {
- private static string[,] matrix =
- {
- {"0","0","0","X","0","X"},
- {"0","X","0","X","0","X"},
- {"0","*","X","0","X","0"},
- {"0","X","0","0","0","0"},
- {"0","0","0","X","X","0"},
- {"0","0","0","X","0","X"}
- };
- public static void Main()
- {
- var startingCell = FindStartingCell();
- bool[,] visited = new bool[matrix.GetLength(0), matrix.GetLength(1)];
- visited[startingCell.X, startingCell.Y] = true;
- var queue = new Queue<Cell>();
- queue.Enqueue(startingCell);
- FillCells(queue, visited);
- PrintMatrix();
- }
- private static void PrintMatrix()
- {
- for (int i = 0; i < matrix.GetLength(0); i++)
- {
- for (int j = 0; j < matrix.GetLength(1); j++)
- {
- Console.Write(matrix[i, j] + " ");
- }
- Console.WriteLine();
- }
- }
- private static void FillCells(Queue<Cell> queue, bool[,] visited)
- {
- while (queue.Count > 0)
- {
- var cell = queue.Dequeue();
- var x = cell.X;
- var y = cell.Y;
- var level = cell.Level;
- matrix[x, y] = level.ToString();
- if (x - 1 >= 0 && matrix[x - 1, y] != "X" && !visited[x - 1, y])
- {
- queue.Enqueue(new Cell() {X = x - 1, Level = level + 1, Y = y});
- visited[x - 1, y] = true;
- }
- if (x + 1 < matrix.GetLength(0) && matrix[x + 1, y] != "X" && !visited[x + 1, y])
- {
- queue.Enqueue(new Cell() {X = x + 1, Level = level + 1, Y = y});
- visited[x + 1, y] = true;
- }
- if (y - 1 >= 0 && matrix[x, y - 1] != "X" && !visited[x, y - 1])
- {
- queue.Enqueue(new Cell() {X = x, Level = level + 1, Y = y - 1});
- visited[x, y - 1] = true;
- }
- if (y + 1 < matrix.GetLength(1) && matrix[x, y + 1] != "X" && !visited[x, y + 1])
- {
- queue.Enqueue(new Cell() {X = x, Level = level + 1, Y = y + 1});
- visited[x, y + 1] = true;
- }
- }
- for (int i = 0; i < matrix.GetLength(0); i++)
- {
- for (int j = 0; j < matrix.GetLength(1); j++)
- {
- if (matrix[i, j] == "0")
- {
- matrix[i, j] = "u";
- }
- }
- }
- }
- private static Cell FindStartingCell()
- {
- var startingCell = new Cell();
- for (int i = 0; i < matrix.GetLength(1); i++)
- {
- for (int j = 0; j < matrix.GetLength(0); j++)
- {
- if (matrix[j, i] == "*")
- {
- startingCell.X = j;
- startingCell.Y = i;
- return startingCell;
- }
- }
- }
- throw new ArgumentException("No such cell found!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement