Advertisement
Mihail78

ZigZag

Dec 9th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class ZigZag02 {
  4.     public static void main(String[] args) {
  5.         Scanner sc = new Scanner(System.in);
  6.         int rows = sc.nextInt();
  7.         int cols = sc.nextInt();
  8.  
  9.         if (rows == 1 || cols == 1){
  10.             System.out.println(getValue(0,0));
  11.             return;
  12.         }
  13.  
  14.         long result = getValue(0,0);
  15.         int row = 1;
  16.         int col = 1;
  17.         int dRow = -1;
  18.         int dCol = +1;
  19.  
  20.         while (!atCorner (row, col, rows, cols)) {
  21.             result += getValue(row, col);
  22.  
  23.             int nextRow = row;
  24.             int nextCol = col + dCol;
  25.             if (nextCol<0 || nextCol > cols - 1) {
  26.                 dCol *= -1;
  27.                 dRow*=-1;
  28.             }
  29.             row += dRow;
  30.             col += dCol;
  31.             dRow *= -1;
  32.         }
  33.         result += getValue(row, col);
  34.         System.out.println(result);
  35.     }
  36.     private static long getValue (int row, int col) {
  37.         int sum = row + col;
  38.         return (long) (sum*3)+1;
  39.     }
  40.     private static boolean atCorner(int row, int col, int rows, int cols) {
  41.         return  ((row <= 0 || row >= rows - 1) && (col <= 0 || col >= cols -1));
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement