0% found this document useful (0 votes)
5 views6 pages

Java Code for Sofa Movement Solver

Uploaded by

shivankyadav479
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

Java Code for Sofa Movement Solver

Uploaded by

shivankyadav479
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

BufferedReader;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class sofa { // Renamed this line to match your filename "[Link]"

private static class State {

final int r1, c1, r2, c2;

public State(int r1, int c1, int r2, int c2) {

this.r1 = r1;

this.c1 = c1;

this.r2 = r2;

this.c2 = c2;

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (o == null || getClass() != [Link]()) return false;


State state = (State) o;

return r1 == state.r1 && c1 == state.c1 && r2 == state.r2 && c2 == state.c2;

@Override

public int hashCode() {

return [Link](r1, c1, r2, c2);

private static class QueueItem {

final State state;

final int steps;

public QueueItem(State state, int steps) {

[Link] = state;

[Link] = steps;

private static int M, N;

private static char[][] grid;

public static void main(String[] args) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

String[] dimensions = [Link]().split(" ");

M = [Link](dimensions[0]);
N = [Link](dimensions[1]);

grid = new char[M][N];

List<int[]> sCoords = new ArrayList<>();

List<int[]> SCoords = new ArrayList<>();

for (int i = 0; i < M; i++) {

String[] line = [Link]().split(" ");

for (int j = 0; j < N; j++) {

grid[i][j] = line[j].charAt(0);

if (grid[i][j] == 's') {

[Link](new int[]{i, j});

grid[i][j] = '0';

} else if (grid[i][j] == 'S') {

[Link](new int[]{i, j});

grid[i][j] = '0';

if ([Link]() != 2 || [Link]() != 2) {

[Link]("Impossible");

return;

[Link](sCoords, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);

State startState = new State([Link](0)[0], [Link](0)[1], [Link](1)[0],


[Link](1)[1]);
[Link](SCoords, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);

State targetState = new State([Link](0)[0], [Link](0)[1],


[Link](1)[0], [Link](1)[1]);

Queue<QueueItem> queue = new ArrayDeque<>();

Set<State> visited = new HashSet<>();

[Link](new QueueItem(startState, 0));

[Link](startState);

while (![Link]()) {

QueueItem currentItem = [Link]();

State currentState = [Link];

int steps = [Link];

if ([Link](targetState)) {

[Link](steps);

return;

int r1 = currentState.r1;

int c1 = currentState.c1;

int r2 = currentState.r2;

int c2 = currentState.c2;

addState(queue, visited, new State(r1 - 1, c1, r2 - 1, c2), steps);

addState(queue, visited, new State(r1 + 1, c1, r2 + 1, c2), steps);


addState(queue, visited, new State(r1, c1 - 1, r2, c2 - 1), steps);

addState(queue, visited, new State(r1, c1 + 1, r2, c2 + 1), steps);

if (r1 == r2) {

if (r1 + 1 < M && grid[r1 + 1][c1] != 'H' && grid[r1 + 1][c2] != 'H') {

addState(queue, visited, new State(r1, c1, r1 + 1, c1), steps);

addState(queue, visited, new State(r1, c2, r1 + 1, c2), steps);

if (r1 - 1 >= 0 && grid[r1 - 1][c1] != 'H' && grid[r1 - 1][c2] != 'H') {

addState(queue, visited, new State(r1 - 1, c1, r1, c1), steps);

addState(queue, visited, new State(r1 - 1, c2, r1, c2), steps);

} else {

if (c1 + 1 < N && grid[r1][c1 + 1] != 'H' && grid[r2][c1 + 1] != 'H') {

addState(queue, visited, new State(r1, c1, r1, c1 + 1), steps);

addState(queue, visited, new State(r2, c1, r2, c1 + 1), steps);

if (c1 - 1 >= 0 && grid[r1][c1 - 1] != 'H' && grid[r2][c1 - 1] != 'H') {

addState(queue, visited, new State(r1, c1 - 1, r1, c1), steps);

addState(queue, visited, new State(r2, c1 - 1, r2, c1), steps);

[Link]("Impossible");

}
private static void addState(Queue<QueueItem> queue, Set<State> visited, State
potentialState, int currentSteps) {

int r1 = potentialState.r1;

int c1 = potentialState.c1;

int r2 = potentialState.r2;

int c2 = potentialState.c2;

if (r1 < 0 || r1 >= M || c1 < 0 || c1 >= N ||

r2 < 0 || r2 >= M || c2 < 0 || c2 >= N ||

grid[r1][c1] == 'H' || grid[r2][c2] == 'H') {

return;

State normalizedState;

if (r1 < r2 || (r1 == r2 && c1 < c2)) {

normalizedState = potentialState;

} else {

normalizedState = new State(r2, c2, r1, c1);

if (![Link](normalizedState)) {

[Link](normalizedState);

[Link](new QueueItem(normalizedState, currentSteps + 1));

Common questions

Powered by AI

Sorting the coordinates in `sCoords` and `SCoords` ensures consistent ordering when creating `State` objects. This standardization is crucial for equality checks and helps maintain the integrity of the problem constraints, where specific positions in the grid need to match for the `startState` and `targetState`. Without identifying a stable order, the same set of coordinates could lead to distinct `State` objects due to differing attribute assignments (`r1`, `c1`, `r2`, `c2`), and the solution would fail to accurately track movements and check for the solution.

The `State` class acts as a representation of the position of two points on the grid, encapsulating their coordinates. It is pivotal for state comparison, equality checking, and hash generation, aiding efficient tracking and management during BFS traversal. The `QueueItem` class adds context by pairing a `State` object with the corresponding number of traversal steps to reach it. This encapsulation enables the BFS queue to maintain both spatial and temporal information about each state exploration phase, facilitating precise step-count tracking and priority execution in line with BFS principles.

During input processing, occurrences of 's' and 'S' in the grid are appended to their respective coordinate lists (`sCoords` for 's', `SCoords` for 'S') and then replaced with '0' in the grid representation. This transformation abstracts the starting and target positions from the rest of the grid operations, simplifying the problem by decoupling these specific navigational targets from incidental obstructions or markers, thus focusing the process on navigation to victory criteria. As a result, the grid mainly retains dynamic route threats ('H's) while rendering comparison and logic operations on key goal markers (`s` and `S`) explicit and separate.

The normalization process ensures consistent representation of `State` objects by ordering the coordinates in a predictable manner. By ordering according to grid position, it prevents different permutations of the same physical state from being treated as distinct. This consistency is vital for accurate state comparison and storage within the `visited` set, as it prevents logically identical but differently ordered states from being added multiple times, which could distort search progression and results.

The `equals()` method in the `State` class overrides the default implementation to provide a specific equality check based on the properties of `State` objects. It first checks if the `this` object and the `other` object are the same with `if (this == o) return true;`. If the tested object is not a `State` instance, it returns false. Otherwise, it checks equality for each attribute (`r1`, `c1`, `r2`, `c2`) to determine if both `State` objects have identical properties, ensuring correct object comparison behavior.

The solution utilizes a set called `visited` to track states that have already been explored. When a new potential state is generated, it normalizes and checks against the `visited` set before adding it to the queue for further exploration. This prevents the BFS algorithm from re-evaluating already processed states, avoiding cyclic paths and redundant computations, thereby optimizing performance and focusing on unexplored paths only. This approach is instrumental in maintaining the efficiency and effectiveness of the solution.

The `addState` method implements constraints to ensure that any potential move is within the bounds of the grid and does not cross into positions marked as impassable ('H'). It checks if the proposed new state’s coordinates are valid grid positions, i.e., `0 <= r1, r2 < M` and `0 <= c1, c2 < N`, and ensures the positions are not blocked by 'H'. These checks are crucial to prevent illegal or nonsensical operations that violate the physical constraints of the problem environment, ensuring only viable paths are pursued.

The BFS algorithm ensures finding the shortest path by exploring nodes layer by layer, thereby expanding paths in breadth before depth. Each time a state is dequeued, it contains the fewest steps possible to reach that state from the start, owing to the step count being incremented one unit per layer. Any encounter with the `targetState` signals that it was reached via the least number of steps necessary because all shorter-length paths have been previously explored. The nature of BFS naturally builds minimal-path solutions in tree structures without needing as backtracking or revisits.

The solution prints "Impossible" if there aren't exactly two lowercase 's' and two uppercase 'S' coordinates identified in the grid, or if all possible states have been explored without reaching the `targetState`. This is valid because the problem's setup requires both pairs for valid start and target configurations. Without these precise conditions, the scenario described by the problem cannot exist or be resolved, thus making further attempts redundant and justifying declaring the task impossible. Additionally, the state exploration can logically conclude that no sequence of moves leads to the `targetState`.

The solution uses a Breadth-First Search (BFS) approach implemented using a queue to explore states incrementally. It enqueues the initial `startState` and iteratively checks all reachable neighboring states by adding valid transitions to the queue. By marking visited states, it avoids reconsidering previously encountered states. The BFS ensures that the first time the algorithm encounters the `targetState`, it does so using the minimum number of steps, as BFS explores states layer by layer, ensuring minimal step exploration.

You might also like