(int[][] matrix, Coordinate origin, Coordinate dest, int x)
| 17 | } |
| 18 | |
| 19 | public static Coordinate findElement(int[][] matrix, Coordinate origin, Coordinate dest, int x) { |
| 20 | if (!origin.inbounds(matrix) || !dest.inbounds(matrix)) { |
| 21 | return null; |
| 22 | } |
| 23 | if (matrix[origin.row][origin.column] == x) { |
| 24 | return origin; |
| 25 | } else if (!origin.isBefore(dest)) { |
| 26 | return null; |
| 27 | } |
| 28 | |
| 29 | /* Set start to start of diagonal and end to the end of the diagonal. Since |
| 30 | * the grid may not be square, the end of the diagonal may not equal dest. |
| 31 | */ |
| 32 | Coordinate start = (Coordinate) origin.clone(); |
| 33 | int diagDist = Math.min(dest.row - origin.row, dest.column - origin.column); |
| 34 | Coordinate end = new Coordinate(start.row + diagDist, start.column + diagDist); |
| 35 | Coordinate p = new Coordinate(0, 0); |
| 36 | |
| 37 | /* Do binary search on the diagonal, looking for the first element greater than x */ |
| 38 | while (start.isBefore(end)) { |
| 39 | p.setToAverage(start, end); |
| 40 | if (x > matrix[p.row][p.column]) { |
| 41 | start.row = p.row + 1; |
| 42 | start.column = p.column + 1; |
| 43 | } else { |
| 44 | end.row = p.row - 1; |
| 45 | end.column = p.column - 1; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /* Split the grid into quadrants. Search the bottom left and the top right. */ |
| 50 | return partitionAndSearch(matrix, origin, dest, start, x); |
| 51 | } |
| 52 | |
| 53 | public static Coordinate findElement(int[][] matrix, int x) { |
| 54 | Coordinate origin = new Coordinate(0, 0); |
no test coverage detected