703281. Countries at war
Here is the detailed Markdown blog post for the "Countries at war" problem:
Countries at War
Summary
Given a list of countries and their relationships (whether they are at war or not), write a program to find all pairs of countries that are currently at war. The input will be in the format of an adjacency matrix, where matrix[i][j] = 1 if country i is at war with country j, and 0 otherwise.
Detailed Explanation
To solve this problem, we can use a simple approach: iterate through each row of the adjacency matrix, and for each country, check all other countries to see if they are at war. If they are, add them to our list of warring countries. Here's a step-by-step breakdown:
- Initialize an empty list
warring_countriesto store all pairs of countries that are at war. - Iterate through each row
iof the adjacency matrix:- For each column
j, check ifmatrix[i][j] == 1. If it is, it means countryiis at war with countryj. - Add the pair
(country_i, country_j)to our listwarring_countries.
- For each column
- Return the list of warring countries.
The time complexity for this solution is O(n^2), where n is the number of countries, since we're iterating through each row and column of the adjacency matrix. The space complexity is O(n^2) as well, since we need to store all pairs of warring countries in our list.
Here's an ASCII art diagram of the adjacency matrix:
| A | B | C | D
-------------------------
A | 0 | 1 | 0 | 0
B | 1 | 0 | 1 | 1
C | 0 | 1 | 0 | 0
D | 0 | 1 | 0 | 0
In this example, countries A and B are at war, as are countries B and C, and countries B and D.
Optimized Solutions
Java
public List<List<String>> findWarringCountries(int[][] matrix) {
List<List<String>> warringCountries = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = i + 1; j < matrix[i].length; j++) {
if (matrix[i][j] == 1) {
warringCountries.add(Arrays.asList(String.valueOf(i), String.valueOf(j)));
}
}
}
return warringCountries;
}