Computer Science/Algorithm2011. 5. 11. 19:18
1로 연결된 도형 내부를 1로 채우기

예제>
입력
00000000000000000000
00111111111111111110
00100000000000000010
00111110000000000010
00000010000000000100
00001100000000000010
00001000000000000010
00001111111111111100
00000000000000000000

출력
00000000000000000000
00111111111111111110
00111111111111111110
00111111111111111110
00000011111111111100
00001111111111111110
00001111111111111110
00001111111111111100
00000000000000000000
 

메인 메소드

List<String> sample = makeSample();
int x = 10; int y = 3;    -> 시작지점은 임의로 만들었다.
char[][] maps = sampleToMaps(sample);
 
mark(x, y, maps);

칸을 채우는 메소드로 재귀호출함

private void mark(int x, int y, char[][] maps)
{
maps[y][x] = '1';
if(x-1 > 0 && '0' == maps[y][x-1]) {
mark(x-1, y, maps);
}
if(x+1 < maps[y].length && '0' == maps[y][x+1]) {
mark(x+1, y, maps);
}
if(y-1 > 0 && '0' == maps[y-1][x]) {
mark(x, y-1, maps);
}
if(y+1 < maps.length && '0' == maps[y+1][x]) {
mark(x, y+1, maps);
}
}


문제를 만드는 메소드
처음부터 2x2 char로 map만들기 불편하기 때문에 만들었다.

private List<String> makeSample()
{
List<String> result = new ArrayList<String>();
result.add("00000000000000000000");
result.add("00111111111111111110");
result.add("00100000000000000010");
result.add("00111110000000000010");
result.add("00000010000000000100");
result.add("00001100000000000010");
result.add("00001000000000000010");
result.add("00001111111111111100");
result.add("00000000000000000000");

return result;
}

문제를 해결할 자료구조에 옮기는 메소드

private char[][] sampleToMaps(List<String> sample)
{
char[][] result = new char[sample.size()][20];
for(int i = 0; i < result.length; ++i){
sample.get(i).getChars(0, sample.get(i).length(), result[i], 0);
}
return result;
}


'Computer Science > Algorithm' 카테고리의 다른 글

insertion sort - c  (0) 2011.05.28
insertion sort - Java  (0) 2011.05.26
binary search - Java  (0) 2011.05.17
binary search - c  (0) 2011.05.16
반전 알고리즘  (0) 2011.05.12
Posted by 준피