// Arup Guha
// 11/17/2014
// Solution to South East Regional D2 Problem: Knight Moves

import java.util.*;

public class knightmoves {

	// How knights move
	final public static int[] DX = {-2,-2,-1,-1,1,1,2,2};
	final public static int[] DY = {-1,1,-2,2,-2,2,-1,1};

	final public static int UNVISITED = -1;

	// Easy access to the grid.
	public static char[][] grid;
	public static int r;
	public static int c;

	public static void main(String[] args) {

		// Read in board.
		Scanner stdin = new Scanner(System.in);
		r = stdin.nextInt();
		c = stdin.nextInt();
		grid = new char[r][];
		for (int i=0; i<r; i++)
			grid[i] = stdin.next().toCharArray();

		// Look for knight and end.
		int start=-1, end=-1;
		for (int i=0; i<r*c; i++) {
			if (grid[i/c][i%c] == 'K') start = i;
			if (grid[i/c][i%c] == 'X') end = i;
		}

		// Here is our result.
		System.out.println(bfs(start, end));
	}

	public static int bfs(int start, int end) {

		// Keep track of distances to each location.
		int[] dist = new int[r*c];
		Arrays.fill(dist, UNVISITED);

		// Initialize BFS.
		dist[start] = 0;
		LinkedList<Integer> q = new LinkedList<Integer>();
		q.offer(start);

		// Run BFS.
		while (q.size() > 0) {

			// Get next item.
			int next = q.poll();
			int nextR = next/c;
			int nextC = next%c;

			// Done!
			if (next == end) return dist[next];

			// Try each direction - only go if it's inbounds, not blocked and we've never been there.
			for (int i=0; i<DX.length; i++) {
				int x = nextR+DX[i];
				int y = nextC+DY[i];
				if (inbounds(x,y) && grid[x][y] != '#' && dist[x*c+y] == UNVISITED) {
					q.offer(x*c+y);
					dist[x*c+y] = dist[next] + 1;
				}
			}
		}

		// Never got there.
		return -1;
	}

	// Returns true iff (x,y) is inbounds of grid.
	public static boolean inbounds(int x, int y) {
		return x >= 0 && x < r && y >= 0 && y < c;
	}
}