|
148 | 148 | // }
|
149 | 149 |
|
150 | 150 | /* Floyd Warshall */
|
151 | | - |
152 | | -// class Solution { |
153 | | -// public int findTheCity(int n, int[][] edges, int distanceThreshold) { |
154 | | -// int[][] dp = new int[n][n]; |
155 | | -// |
156 | | -// // Initialize dp |
157 | | -// for (int i = 0; i < n; i++) { |
158 | | -// Arrays.fill(dp[i], Integer.MAX_VALUE); |
159 | | -// dp[i][i] = 0; |
160 | | -// } |
161 | | -// |
162 | | -// for (int[] edge : edges) { |
163 | | -// // Fill dp with from to edge grid; dp[from][to] = weight |
164 | | -// dp[edge[0]][edge[1]] = edge[2]; |
165 | | -// dp[edge[1]][edge[0]] = edge[2]; |
166 | | -// } |
167 | | -// |
168 | | -// // Find all shortest path |
169 | | -// for (int detour = 0; detour < n; detour++) { |
170 | | -// for (int from = 0; from < n; from++) { |
171 | | -// for (int to = 0; to < n; to++) { |
172 | | -// // Update edge path if detour city is shorter than direct |
173 | | -// if (dp[from][to] > dp[from][detour] + dp[detour][to]) |
174 | | -// dp[from][to] = dp[from][detour] + dp[detour][to]; |
175 | | -// } |
176 | | -// } |
177 | | -// } |
178 | | -// |
179 | | -// int maxVisits = n + 1; |
180 | | -// int cityWithLesserNeighbors = -1; |
181 | | -// for(int from = 0; from < n; from++) { |
182 | | -// // Get all neighboring cities with less than distanceThreshold edge |
183 | | -// int neighborCitiesWithinLimit = 0; |
184 | | -// for(int to = 0; to < n; to++) { |
185 | | -// if(dp[from][to] <= distanceThreshold) |
186 | | -// neighborCitiesWithinLimit++; |
187 | | -// } |
188 | | -// if(neighborCitiesWithinLimit <= maxVisits){ |
189 | | -// cityWithLesserNeighbors = from; |
190 | | -// maxVisits = Math.min(maxVisits, neighborCitiesWithinLimit); |
191 | | -// } |
192 | | -// } |
193 | | -// |
194 | | -// return cityWithLesserNeighbors; |
195 | | -// } |
196 | | -// } |
197 | | - |
198 | | - |
199 | 151 | class Solution {
|
200 | 152 | public int findTheCity(int n, int[][] edges, int distanceThreshold) {
|
| 153 | + // This needs to be a float because it needs to store the Integer.MAX_VALUE. |
| 154 | + // Else if this is int, adding a positive number to the max value an integer |
| 155 | + // can handle, the bits will overflow and becomes a negative number. |
| 156 | + // Alternatively, instead of the MAX_VALUE as a placeholder, since the |
| 157 | + // constraint for distanceThreshold <= 10^4, we can initialize it with |
| 158 | + // anything greater than the threshold value (i.e., 10001). |
201 | 159 | float[][] dp = new float[n][n];
|
202 | 160 |
|
203 | 161 | // Initialize dp
|
204 | 162 | for (int i = 0; i < n; i++) {
|
205 | | - Arrays.fill(dp[i], Integer.MAX_VALUE); |
| 163 | + Arrays.fill(dp[i], 10001); |
206 | 164 | dp[i][i] = 0;
|
207 | 165 | }
|
208 | 166 |
|
|
0 commit comments