[Timus] 1319 Hotel

The problem statement is here: http://acm.timus.ru/problem.aspx?space=1&num=1319.

Similar problem to 1313 Some Words about Sport , in this problem instead of traversing the table diagonally up we have to print the matrix diagonally downwards.

public class Task1319 {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.nextInt();
        // The resulting matrix.
        int[][] table = new int[n][n];

        int label = 1;

        // Traverse the first element of each column from n-1 to 0 and then
        // first element of each row from 1 to n-1.
        for (int i = 0; i < 2 * n - 1; i++) {
            int col = n-1-i;
            int row = 0;
            // if col is -ve then we need to go down in the row.
            if(col<0) {
                row = -col;
                col = 0;
            }
            while(row<n && col<n) {
                table[row][col] = label;
                label++;
                row++;
                col++;
            }
        }

        for (int i = 0; i < n; i++) {
            out.println(table[i]);
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.