Thursday, July 28, 2016

Nearest Locker Distance

Practice on loops.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class NearestLockerDistance {
 static int[][] rotateMatrix(int[][] matrix) {
  int[][] result = new int[matrix[0].length][matrix.length];
  for (int r = 0; r < matrix.length; r++) {
   for (int c = 0; c < matrix[0].length; c++) {
    result[c][r] = matrix[r][c];
   }
  }
  return result;
 }

 static int[][] getLockerDistanceGrid(int cityLength, int cityWidth,
   int[] lockerXCoordinates, int[] lockerYCoordinates) {
  if (lockerXCoordinates == null || lockerYCoordinates == null
    || lockerXCoordinates.length != lockerYCoordinates.length)
   return null;
  int[][] city = new int[cityWidth][cityLength];
  // initialize city to biggest numbers
  for (int i = 0; i < city[0].length; i++)
   // x
   for (int j = 0; j < city.length; j++)
    // y
    city[j][i] = Integer.MAX_VALUE;

  // mark the locker's distance. it also remembers the location of lockers
  for (int i = 0; i < lockerXCoordinates.length; i++)
   city[lockerYCoordinates[i] - 1][lockerXCoordinates[i] - 1] = 0;
  // calculate for each locker
  for (int i = 0; i < lockerXCoordinates.length; i++) {
   calcDistance(city, lockerYCoordinates[i], lockerXCoordinates[i]);
  }
  city = rotateMatrix(city);
  return city;
 }

 static void calcDistance(int[][] city, int y, int x) {
  y = y - 1;
  x = x - 1; // this is place can be optimized
  for (int i = 0; i < city[0].length; i++)
   // x
   for (int j = 0; j < city.length; j++)// y
   {
    if (city[j][i] != 0) {
     city[j][i] = Math.min(city[j][i], Math.abs(j - y) + Math.abs(i - x));
    }
   }

 }

}

No comments: