static void Main(string[] args)
    {
        Dictionary <int, RoomLayout> roomTypes = DefaultRoomTypes();

        string[] inputs;
        inputs = Console.ReadLine().Split(' ');
        int dungeonWidth  = int.Parse(inputs[0]); // number of columns.
        int dungeonHeight = int.Parse(inputs[1]); // number of rows.

        int[,] dungeonMap = new int[dungeonWidth, dungeonHeight];
        for (int i = 0; i < dungeonHeight; i++)
        {
            string[] LINE = Console.ReadLine().Split(' '); // represents a line in the grid and contains W integers. Each integer represents one room of a given type.
            for (int j = 0; j < dungeonWidth; j++)
            {
                dungeonMap[j, i] = int.Parse(LINE[j]);
            }
        }
        int EX = int.Parse(Console.ReadLine()); // the coordinate along the X axis of the exit (not useful for this first mission, but must be read).

        // game loop
        while (true)
        {
            inputs = Console.ReadLine().Split(' ');
            int    XI  = int.Parse(inputs[0]);
            int    YI  = int.Parse(inputs[1]);
            string POS = inputs[2];

            RoomLayout currentRoomType = roomTypes[dungeonMap[XI, YI]];
            List <int> newDirections   = currentRoomType.AvailableExits(POS);

            if (newDirections.Count == 1)
            {
                switch (newDirections[0])
                {
                case 0:
                    YI -= 1;
                    break;

                case 1:
                    XI += 1;
                    break;

                case 2:
                    YI += 1;
                    break;

                case 3:
                    XI -= 1;
                    break;
                }
            }

            Console.WriteLine("" + XI + " " + YI);
        }
    }