|
| 1 | +package javacode.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +// [Problem] https://leetcode.com/problems/where-will-the-ball-fall |
| 6 | +class WhereWillTheBallFall { |
| 7 | + // Matrix |
| 8 | + // O(m * n) time, O(n) space |
| 9 | + // where m = row size, n = column size |
| 10 | + public int[] findBall(int[][] grid) { |
| 11 | + int rowSize = grid.length, colSize = grid[0].length; |
| 12 | + int[] ballPositions = new int[colSize]; |
| 13 | + for (int ball = 0; ball < colSize; ball++) { |
| 14 | + int row = 0, col = ball; |
| 15 | + while (row < rowSize) { |
| 16 | + int direction = grid[row][col]; |
| 17 | + int nextCol = col + direction; |
| 18 | + if (nextCol < 0 || nextCol >= colSize || grid[row][nextCol] != direction) { |
| 19 | + ballPositions[ball] = -1; |
| 20 | + break; |
| 21 | + } |
| 22 | + row++; |
| 23 | + col = nextCol; |
| 24 | + } |
| 25 | + if (row == rowSize) { |
| 26 | + ballPositions[ball] = col; |
| 27 | + } |
| 28 | + } |
| 29 | + return ballPositions; |
| 30 | + } |
| 31 | + |
| 32 | + // Test |
| 33 | + public static void main(String[] args) { |
| 34 | + WhereWillTheBallFall solution = new WhereWillTheBallFall(); |
| 35 | + |
| 36 | + int[][] input = { |
| 37 | + {1, 1, 1, -1, -1}, |
| 38 | + {1, 1, 1, -1, -1}, |
| 39 | + {-1, -1, -1, 1, 1}, |
| 40 | + {1, 1, 1, 1, -1}, |
| 41 | + {-1, -1, -1, -1, -1} |
| 42 | + }; |
| 43 | + int[] expectedOutput = {1, -1, -1, -1, -1}; |
| 44 | + int[] actualOutput = solution.findBall(input); |
| 45 | + |
| 46 | + System.out.println("Test passed? " + Arrays.equals(expectedOutput, actualOutput)); |
| 47 | + } |
| 48 | +} |
0 commit comments