-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
44 lines (39 loc) · 1.23 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
// github.com/RodneyShag
import java.util.Scanner;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
while (T-- > 0) {
int N = scan.nextInt();
char [][] grid = new char[N][N];
for (int i = 0; i < N; i++) {
String str = scan.next();
for (int j = 0; j < str.length(); j++) {
grid[i][j] = str.charAt(j);
}
}
System.out.println(canConvert(grid) ? "YES" : "NO");
}
scan.close();
}
/* Uses Greedy Approach */
private static boolean canConvert(char [][] grid) {
/* Sort each row */
int rows = grid.length;
int cols = grid[0].length;
for (int row = 0; row < rows; row++) {
Arrays.sort(grid[row]);
}
/* Check columns for lexicographic ordering */
for (int row = 1; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (grid[row][col] < grid[row-1][col]) {
return false;
}
}
}
return true;
}
}