Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- public class ChessBoard {
- public static void Main() {
- int n = int.Parse(Console.ReadLine().Trim());
- char[,] board = new char[n, n];
- (int, int) start = (0, 0), finish = (0, 0);
- for (int i = 0; i < n; i++) {
- string line = Console.ReadLine().Trim();
- for (int j = 0; j < n; j++) {
- board[i, j] = line[j];
- if (board[i, j] == 'S') start = (i, j);
- else if (board[i, j] == 'F') finish = (i, j);
- }
- }
- int result = BFS(board, start, finish, n);
- Console.WriteLine(result);
- }
- private static int BFS(char[,] board, (int, int) start, (int, int) finish, int n) {
- var directionsKing = new int[,] { {1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1} };
- var directionsKnight = new int[,] { {1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1} };
- var queue = new Queue<(int, int, char, int)>();
- var visited = new HashSet<(int, int, char)>();
- queue.Enqueue((start.Item1, start.Item2, 'K', 0)); // Start as a knight
- visited.Add((start.Item1, start.Item2, 'K'));
- while (queue.Count > 0) {
- var (x, y, type, moves) = queue.Dequeue();
- if (x == finish.Item1 && y == finish.Item2) return moves;
- int[,] directions = type == 'K' ? directionsKnight : directionsKing;
- for (int i = 0; i < directions.GetLength(0); i++) {
- int newX = x + directions[i, 0];
- int newY = y + directions[i, 1];
- if (newX >= 0 && newY >= 0 && newX < n && newY < n && board[newX, newY] != 'W') {
- char newType = type;
- if (board[newX, newY] == 'K') newType = 'K';
- else if (board[newX, newY] == 'G') newType = 'G';
- if (!visited.Contains((newX, newY, newType))) {
- visited.Add((newX, newY, newType));
- queue.Enqueue((newX, newY, newType, moves + 1));
- }
- }
- }
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement