HackerRank 'Grid Challenge' Solution

by Srikant Padala on June 27, 2016, 11:48 am


Explanation


Sort each row in ascending order first and then check if the columns have sorted order.


Grid Challenge Problem Statement

Video

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

string isLexicographicalSortPossible(vector<string> &rows) {
    int n = rows.size();
    for(int i=0; i < n; i++) {
        sort(rows[i].begin(), rows[i].end());
    }
    for(int j=0; j < n; j++) {
        for(int i=0; i < n - 1; i++) {
            if(rows[i][j] > rows[i+1][j]) return "NO";
        }
    }
    return "YES";
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int t,n;
    cin >> t;
    while(t--) {
        cin >> n;
        vector<string> rows(n);
        for(int i=0; i < n; i++) {
            cin >> rows[i];
        }
        cout << isLexicographicalSortPossible(rows) << endl;
    }
    return 0;
}

Coming Soon.