Programming/Code
[Java] BlobSize Algorithm 문제
MIN JOON
2017. 10. 12. 10:28
N*N 맵에서 주어진 초기 좌표값과 상,하,좌,우,대각선으로 연결되어있는 BLOB의 Size 구하는 문제
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class BlobSize {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 0, y = 0;
int positionX = 0, positionY = 0;
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(new File("src/com/minjoon/Problem/BlobSize/map.txt"))));
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
String[] xy = br.readLine().split(" ");
x = Integer.parseInt(xy[0]);
y = Integer.parseInt(xy[1]);
String[] position = br.readLine().split(" ");
positionX = Integer.parseInt(position[0]);
positionY = Integer.parseInt(position[1]);
String[][] map = new String[x][y];
for (int i = 0; i < x; i++) {
String line = br.readLine();
String[] pixel = line.split(" ");
for (int j = 0; j < y; j++) {
map[i][j] = pixel[j];
}
}
printMap(map);
System.out.println();
int size = countSize(map, positionX, positionY);
printMap(map);
System.out.println();
System.out.println(size);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int countSize(String[][] map, int x, int y) {
int size = 0;
if (x < 0 || y < 0 || x >= map.length || y >= map[0].length) {
return size;
} else if (map[x][y].equals("0")) {
return size;
} else if (map[x][y].equals("1")) {
map[x][y] = "9";
size++;
size += countSize(map, x - 1, y);
size += countSize(map, x - 1, y + 1);
size += countSize(map, x, y + 1);
size += countSize(map, x + 1, y + 1);
size += countSize(map, x + 1, y);
size += countSize(map, x + 1, y - 1);
size += countSize(map, x, y - 1);
size += countSize(map, x - 1, y - 1);
}
return size;
}
public static void printMap(String[][] map) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
// map.txt
// 8 8 N*N map
// 3 5 base poiont
// 1 0 0 0 0 0 0 1
// 0 1 1 0 0 1 0 0
// 1 1 0 0 1 0 1 0
// 0 0 0 0 0 1 0 0
// 0 1 0 1 0 1 0 0
// 0 1 0 1 0 1 0 0
// 1 0 0 0 1 0 0 1
// 0 1 1 0 0 1 1 1
}