diff --git a/forklift_crane.java b/forklift_crane.java new file mode 100644 index 0000000..9385271 --- /dev/null +++ b/forklift_crane.java @@ -0,0 +1,100 @@ +import java.util.*; + +class Solution { + char[][] grid; + boolean[][] visited; + int n, m; + int[] dx = {0, 0, 1, -1}; + int[] dy = {1, -1, 0, 0}; + public int solution(String[] storage, String[] requests) { + n = storage.length; + m = storage[0].length(); + // 여백 포함 grid 초기화 (n+2, m+2), 테두리는 '0' + grid = new char[n + 2][m + 2]; + for (char[] row : grid) Arrays.fill(row, '0'); + for(int i=0;iqueue = new ArrayDeque<>(); + queue.add(new int[]{0,0}); //외부취급 모서리 + visited[0][0] = true; + while (!queue.isEmpty()) { + int[] cur = queue.poll(); + int x = cur[0], y = cur[1]; + + for (int dir = 0; dir < 4; dir++) { + int nx = x + dx[dir]; + int ny = y + dy[dir]; + + // 범위 체크, 이미 방문했는지 체크 + if (nx < 0 || nx >= n+2 || ny < 0 || ny >= m+2) + continue; + if (visited[nx][ny]) + continue; + + // 빈 공간('0')만 타고 퍼져나감 + if (grid[nx][ny] != '0') + continue; + + visited[nx][ny] = true; + queue.add(new int[]{nx, ny}); + } + } + } + + public void forklift(char type) { + bfs();// 먼저 외부 연결 상태 갱신 + List toRemove = new ArrayList<>(); + + for(int i=1;i<=n;i++){ + for(int j=1;j<=m;j++){ + if(grid[i][j]!=type) + continue; + for (int dir = 0; dir < 4; dir++) { + int nx = i + dx[dir]; + int ny = j + dy[dir]; + if (visited[nx][ny]) { + toRemove.add(new int[]{i, j}); + break; + } + } + } + } + // 모아둔 위치들 한꺼번에 제거 + for (int[] pos : toRemove) { + grid[pos[0]][pos[1]] = '0'; + } + } + + public void crane(char type) { + //grid를 훑으면서 type인 칸을 전부 '0'으로 변경 + for(int i=1;i<=n;i++){ + for(int j=1;j<=m;j++){ + if(grid[i][j]==type){ + grid[i][j]='0'; + } + } + } + } +}