Question
The Sliding Tiles puzzle consists of a rectangular grid with marked square cells. A cell can be empty or hold a tile with a letter
The Sliding Tiles puzzle consists of a rectangular grid with marked square cells. A cell can be empty or hold a tile with a letter on it. Figure 1 shows an example.
A player can slide a tile to a neighboring empty cell, up, down, left, or right. Let us call a configuration of tiles "packed" if no tile has a neighboring empty cell above or to the left of it. Figure 2 shows an example of a packed grid.
In a computer model of the game, the grid of cells is represented by a 2D array. A tile is represented by a one-letter literal String object; an empty cell holds a null.
A)Write a static boolean method isPacked that returns true if a given configuration of tiles is "packed" otherwise it returns false.
Complete the isPacked method below.
Question 4(a)
/** Returns true if the configuration of tiles represented * by the 2D array tiles is packed, that is, any element * that is not null does not have a null in the same * column in the previous row or in the previous column * in the same row; otherwise returns false. * Precondition: tiles is not empty. */ public static boolean isPacked(String[][] tiles)
B)To pack a given configuration of tiles, we can scan the whole grid row by row, starting at the top row, and each row from left to right. When we encounter a tile, we move the tile by sliding it up to the neighboring empty cell as far as possible, then to the left to the neighboring empty cell as far as possible. Write a private helper method moveTile that helps to implement this algorithm. Complete the moveTile method below.
Question 4(b)
/** Relocates the tile at position (row, col) by first * "sliding" it up several times to the previous row * in the same column, as long as the cell there is empty; * then sliding the tile to the left several times to * the previous column in the same row, as long as the * cell there is empty. * Precondition: The 2D array tiles is not empty; the cell * at location (row, col) holds a tile. */ private static void moveTile(String[][] tiles, int row, int col)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started