CS1020 Island Lab 1 Ex 3

Link to the question – Island Lab 1 Ex 3

import java.util.*;



class Island {

	
	static int xTSize, yTSize = 0;
	static int[][] map;
	public static void main(String[] args){

		Scanner sc = new Scanner(System.in);


		xTSize = sc.nextInt();
		yTSize = sc.nextInt();
		map = new int[xTSize][yTSize];
		for (int i = 0; i < xTSize; i++){
			for (int l = 0; l < yTSize;l++)
				map[i][l] = sc.nextInt();
		}

		//solve
		int island = 0;
		for (int i = 0; i < xTSize; i++){
			for (int l = 0; l < yTSize;l++){
				if (map[i][l] == 1){				
					if (checkIsland(i,l))
						island++;
				}
			}
		}
		System.out.println(island);
	}

	public static boolean checkIsland(int x, int y){
		//check right
		int islandXSize = 1;
		boolean seaFound = false;
		int count = 0;
		while (!seaFound){
			count++;
			if ((x + count) >= xTSize){
				seaFound = true;
				islandXSize = count - 1;
				break;
			}
			if (map[x + count][y] != 1){
				seaFound = true;
				islandXSize = count - 1;
				break;
			}
		}
		//check below
		int islandYSize = 1;
		seaFound = false;
		count = 0;
		while (!seaFound){
			count++;
			if ((y + count) >= yTSize){
				seaFound = true;
				islandYSize = count - 1;
				break;
			}
			if (map[x][y + count] != 1){
				seaFound = true;
				islandYSize = count - 1;
				break;
			}
		}
		islandXSize++;
		islandYSize++;
		//if (x == 4 && y == 5){ System.out.println(islandXSize); System.out.println(islandYSize); }
		if ((islandXSize * islandYSize) >= 2){
			demolishIsland(x,y,islandXSize,islandYSize);
			return true;
		}else
			return false;
	}

	public static void demolishIsland(int x, int y, int xSize, int ySize){
		//System.out.print("size "); System.out.print(xSize); System.out.println(ySize); 
		for (int i = 0; i <xSize; i++){
			for (int l = 0; l < ySize; l++){
				map[i + x][l + y] = 0;
			}
		}
		//for (int i = 0; i < xTSize; i++){
		//	for (int l = 0; l < yTSize;l++)
		//		System.out.print(map[i][l]);
		//	System.out.println();
		//}
	}

}
Advertisements
This entry was posted in NUS, SoC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s