×

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix.

An hour glass is made up of seven cells arranged in the following pattern.
    A B C
      D
    E F G

Examples:

Input : 1 1 1 0 0 
            0 1 0 0 0 
            1 1 1 0 0 
            0 0 0 0 0 
            0 0 0 0 0 
Output : 7
The hour glass below shows the maximum amount:
1 1 1 
  1
1 1 1
Input : 0 3 0 0 0
           0 1 0 0 0
           1 1 1 0 0
           0 0 2 4 4
           0 0 0 2 4
Output : 11
The hour glass below shows the maximum amount:
1 0 0
  4
0 2 4

Approach:

The concept of the hourglass implies that the number of rows and columns must be equal to three. We may say that counting the total number of hourglasses in a matrix equals counting the number of potential top left cells in an hourglass. In an hourglass, the number of top-left cells equals (R-2)*(C-2). As a result, the total number of hourglasses in a matrix is (R-2)*(C-2).

mat[][] = 2 3 0 0 0 
          0 1 0 0 0
          1 1 1 0 0 
          0 0 2 4 4
          0 0 0 2 0
Possible hour glass are :
2 3 0  3 0 0   0 0 0  
  1      0       0 
1 1 1  1 1 0   1 0 0 


0 1 0  1 0 0  0 0 0 
  1      1      0  
0 0 2  0 2 4  2 4 4 


1 1 1  1 1 0  1 0 0
  0      2      4
0 0 0  0 0 2  0 2 0

Consider each top left cell of an hourglass one at a time. We compute the sum of the hourglass created by each cell. Finally, return the highest sum.

The below is an implementation of the following concept:

Hourglass.java

// Java application for determining the maximum
// hour glass sum in matrix
import java.io.*;
class Hourglass {	
static int R = 5;
static int C = 5;
// Returns the greatest possible sum of
// ar[][] hour glass
static int findMaxSum(int [][]mat)
{
	if (R < 3 || C < 3){
		System.out.println("Not possible");
		System.exit(0);
	}
	//The loop is executed here (R-2)*(C-2)
	// considering several situations
	// hourglass cells in the upper left.
	int max_sum = Integer.MIN_VALUE;
	for (int u = 0; u < R - 2; u++)
	{
		for (int v = 0; v < C - 2; v++)
		{
			// Using mat[u][v] as a benchmark
			// The hour glass's left cell.
			int sum = (mat[u][v] + mat[u][v + 1] +
					mat[u][v + 2]) + (mat[u + 1][v + 1]) +
					(mat[u + 2][v] + mat[u + 2][v + 1] +
					mat[u + 2][v + 2]);
			// If the previous total is less than
			// then update the current total
			// new total in max_sum
			max_sum = Math.max(max_sum, sum);
		}
	}
	return max_sum;
}
	// Driver code
	static public void main (String[] args)
	{
		int [][]mat = {{1, 2, 3, 0, 0},
					{0, 0, 0, 0, 0},
					{2, 1, 4, 0, 0},
					{0, 0, 0, 0, 0},
					{1, 1, 0, 1, 0}};
		int res = findMaxSum(mat);
		System.out.println("Hour glass maximum sum = "+ res);
	}	
}

Output:

Hourglass problem in Java

Hourglass.java

import java.util.*;
class Hourglass
{
  public static void main(String[]args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("The number of rows: ");
    int rows = scan.nextInt();    
    System.out.print("The number of columns: ");
    int columns = scan.nextInt();
    int[][]matrix = new int[rows][columns];
    System.out.println("Enter the Matrix components: ");    
    for(int u = 0; u < rows; u++)
    {
      for(int v = 0; v < columns; v++)
      {
        matrix[u][v]=scan.nextInt();
      }
    }
    int sum = 0,max = 0;
    for(int u = 0; u < rows - 2; u++)
    {
      for(int v = 0; v < columns - 2; v++)
      {
        sum = (matrix[u][v] + matrix[u][v + 1] + matrix[u][v + 2]) + (matrix[u + 1][v + 1]) + (matrix[u + 2][v] + matrix[u + 2][v + 1] + matrix[u + 2][v + 2]);       
        if(sum > max)
        {
          max = sum;
        }
      }
    }
    System.out.println("The largest amount in the hourglass is: "+max);
  }
}

Output:

Hourglass problem in Java

Related Topics

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.