|
| 1 | +package com.eprogrammerz.examples.algorithm.crackingCoding; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Objects; |
| 9 | + |
| 10 | +import static org.hamcrest.CoreMatchers.is; |
| 11 | +import static org.junit.Assert.assertEquals; |
| 12 | +import static org.junit.Assert.assertThat; |
| 13 | + |
| 14 | +/** |
| 15 | + * Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. |
| 16 | + * The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. |
| 17 | + * Design an algorithm to find a path for the robot from the top left to the bottom right. |
| 18 | + */ |
| 19 | +public class RobotInGrid { |
| 20 | + public List<Pair> findPath(int[][] grid) { |
| 21 | + List<Pair> path = new ArrayList<>(); |
| 22 | + if (grid == null) return path; |
| 23 | + |
| 24 | + findPath(grid, 0, 0, path); |
| 25 | + return path; |
| 26 | + } |
| 27 | + |
| 28 | + private boolean findPath(int[][] grid, int row, int col, List<Pair> path) { |
| 29 | + if (row >= grid.length || col >= grid[0].length || grid[row][col] == 1) { |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + boolean isAtEnd = row == grid.length - 1 && col == grid[0].length - 1; |
| 34 | + |
| 35 | + if (isAtEnd || findPath(grid, row + 1, col, path) || findPath(grid, row, col + 1, path)) { |
| 36 | + path.add(0, new Pair(row, col)); |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + class Pair { |
| 44 | + int x; |
| 45 | + int y; |
| 46 | + |
| 47 | + Pair(int x, int y) { |
| 48 | + this.x = x; |
| 49 | + this.y = y; |
| 50 | + } |
| 51 | + |
| 52 | + @Override |
| 53 | + public boolean equals(Object obj) { |
| 54 | + if (!(obj instanceof Pair)) return false; |
| 55 | + |
| 56 | + Pair pair = (Pair) obj; |
| 57 | + |
| 58 | + return this.x == pair.x && this.y == pair.y; |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public String toString() { |
| 63 | + return "(" + x + ", " + y + ")"; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + @Test |
| 68 | + public void testFindPathInGrid() { |
| 69 | + int[][] grid = new int[][]{ |
| 70 | + {0, 0, 0}, |
| 71 | + {1, 1, 0}, |
| 72 | + {0, 0, 0} |
| 73 | + }; |
| 74 | + List<Pair> path = findPath(grid); |
| 75 | + |
| 76 | + List<Pair> expected = new ArrayList<>(Arrays.asList(new Pair(0, 0), new Pair(0, 1), new Pair(0, 2), new Pair(1, 2), new Pair(2, 2))); |
| 77 | + assertThat(expected, is(path)); |
| 78 | + } |
| 79 | + |
| 80 | +} |
0 commit comments