forked from RyanFehr/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
58 lines (51 loc) · 1.97 KB
/
Solution.java
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
51
52
53
54
55
56
57
58
//Problem: https://www.hackerrank.com/challenges/organizing-containers-of-balls
//Java 8
/*
Initial Thoughts: We can sum each column to get the
number of each type of ball, then
we can sum horizontally to get the
size of all of the containers, and
if the two sets of numbers don't match
then it is impossible
Time Complexity: O(n^2) //We must look at every ball in a n*n matrix
Space Complexity: O(n^2) //We dynamically store them in sets
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int a0 = 0; a0 < q; a0++){
///////////BUILD THE INPUT MATRIX///////////
int n = in.nextInt();
int[][] M = new int[n][n];
for(int M_i=0; M_i < n; M_i++){
for(int M_j=0; M_j < n; M_j++){
M[M_i][M_j] = in.nextInt();
}
}
////////////////////////////////////////////
//Create a bag for the amount of each ball and the sizes of containers
LinkedList<Integer> containers = new LinkedList<>();
LinkedList<Integer> balls = new LinkedList<>();
for(int i = 0; i < n; i++){
int rowSum = 0;
int colSum = 0;
for(int j = 0; j < n; j++){
rowSum += M[i][j];
colSum += M[j][i];
}
balls.add(colSum);
containers.add(rowSum);
}
//Check if the two bags are equal
containers.removeAll(balls);
if(containers.isEmpty()) System.out.println("Possible");
else System.out.println("Impossible");
}
}
}