(Hacker Rank) Grid Challenge - Solution

Link to the problem: https://www.hackerrank.com/challenges/grid-challenge

Since it is only possible to swap elements in the same row, each row in the input matrix is sorted. Then, it is only necessary to check if every row and column is lexicographically sorted.


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 sc = new Scanner(System.in);
       
        int numTests = sc.nextInt();
        for (int i = 0; i < numTests; i++) {
            int n = sc.nextInt();
            char[][] matrix = new char[n][n];
            for (int j = 0; j < n; j++) {
                String line = sc.next();
                char[] array = line.toCharArray();
                Arrays.sort(array);
                for (int k = 0; k < n; k++) {
                    matrix[j][k] = array[k];
                }
            }
           
            boolean not = false;
            for (int j = 0; j < n && !not; j++) {
                for (int k = 0; k < n-1 && !not; k++) {
                    if (matrix[j][k] > matrix[j][k+1]) {
                        not = true;
                        break;
                    }
                }
            }
            for (int j = 0; j < n && !not; j++) {
                for (int k = 0; k < n-1 && !not; k++) {
                    if (matrix[k][j] > matrix[k+1][j]) {
                        not = true;
                        break;
                    }
                }
            }
           
            if (not) {
                System.out.println("NO");
            }
            else {
                System.out.println("YES");
            }
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução