Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: Read the mass data and find the number of islands

Java Basic: Exercise-237 with Solution

There are 10 vertical and horizontal squares on a plane. Each square is painted blue and green. Blue represents the sea, and green represents the land. When two green squares are in contact with the top and bottom, or right and left, they are said to be ground. The area created by only one green square is called "island". For example, there are five islands in the figure below.
Write a Java program to read the mass data and find the number of islands.

Input:
A single data set is represented by 10 rows of 10 numbers representing green squares as 1 and blue squares as zeros.
Output: For each data set, output the number of islands.

Pictorial Presentation:

Java Basic Exercises: Read the mass data and find the number of islands.

Sample Solution:

Java Code:

  import java.util.Scanner;

public class test {

	public static boolean[][] map;

	public static int[][] move = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

	public static void fds(int i, int j){
		map[i][j] = false;
		for(int k=0;k<4;k++){
			int i2 = i+move[k][0];
			int j2 = j+move[k][1];
			if(0<=i2&&i2<10&&0<=j2&&j2<10&&map[i2][j2])fds(i2,j2);
		}
	}
	public static void main(String[] args) {
		System.out.println("Input 10 rows of 10 numbers representing green squares (island) as 1 and blue squares (sea) as zeros");
		Scanner sc = new Scanner(System.in);
				map = new boolean[10][10];
			for(int i=0;i<10;i++){
				char[] s = sc.next().toCharArray();
				for(int j=0;j<10;j++){
					map[i][j] = s[j]=='1';
				}
			}
			int x = 0;
			for(int i=0;i<10;i++){
				for(int j=0;j<10;j++){
					if(map[i][j]){
						fds(i, j);
						x++;
					}
				}
			}
			System.out.println("Number of islands:");   
			System.out.println(x);
	}
}

Sample Output:

Input 10 rows of 10 numbers representing green squares (island) as 1 and blue squares (sea) as zeros
1100000111
1000000111
0000000111
0010001000
0000011100
0000111110
0001111111
1000111110
1100011100
1110001000
Number of islands:
5

Flowchart:

Flowchart: Read the mass data and find the number of islands.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to sum of all numerical values (positive integers) embedded in a sentence.
Next: Write a Java program to restore the original string by entering the compressed string with this rule.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe