-
Java 11967 불켜기PS 2023. 8. 25. 15:30
https://www.acmicpc.net/problem/11967
11967번: 불켜기
(1, 1)방에 있는 스위치로 (1, 2)방과 (1, 3)방의 불을 켤 수 있다. 그리고 (1, 3)으로 걸어가서 (2, 1)방의 불을 켤 수 있다. (2, 1)방에서는 다시 (2, 2)방의 불을 켤 수 있다. (2, 3)방은 어두워서 갈 수 없으
www.acmicpc.net
로직은 아래와 같다.
1. 방의 좌표 값들을 2차원 Arraylist에 저장한 뒤 0, 0 에서부터 bfs 탐색을 시작한다.
2. 큐에서 꺼낸 좌표 값을 x,y라고 하겠다. 방의 좌표가 있는 Arraylist[x][y]에는 불을 켤 수 있는 좌표가 저장되어 있다.
for each문으로 켤 수 있는 모든 좌표에 불을 켜준다.
3. 상,하,좌,우 탐색이 가능한 곳을 찾아서 큐에 넣어준다.
4. 모든 탐색이 완료되었고, 불을 켠 곳이 있다면 bfs를 재귀호출한다. (지나온 경로에 대해서는 재탐색이 불가하기에)
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.*; public class Main { static int n, m; static boolean[][] light; static boolean[][] visited; static int[] dx = {-1, 0, 1, 0}; static int[] dy = {0, 1, 0, -1}; static ArrayList<Node>[][] list; static class Node { int x; int y; public Node (int x, int y){ this.x = x; this.y = y; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); list = new ArrayList[n][n]; light = new boolean[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ list[i][j] = new ArrayList<>(); } } for(int i = 0; i < m; i++){ st = new StringTokenizer(br.readLine()); int nx = Integer.parseInt(st.nextToken())-1; int ny = Integer.parseInt(st.nextToken())-1; int tx = Integer.parseInt(st.nextToken())-1; int ty = Integer.parseInt(st.nextToken())-1; Node node = new Node(tx, ty); list[nx][ny].add(node); } System.out.println(bfs() + 1); } static int bfs(){ Queue<Node> q = new LinkedList<>(); q.add(new Node(0, 0)); int tmp = 0; visited = new boolean[n][n]; visited[0][0] = true; light[0][0] = true; boolean isTurnOn = false; while(!q.isEmpty()){ Node poll = q.poll(); for(Node node : list[poll.x][poll.y]){ if(!light[node.x][node.y]){ tmp++; light[node.x][node.y] = true; isTurnOn = true; } } for(int i = 0; i < 4; i++){ int nx = poll.x + dx[i]; int ny = poll.y + dy[i]; if(nx < 0 || ny < 0 || nx >= n || ny >= n) continue; if(visited[nx][ny] || !light[nx][ny]) continue; q.add(new Node(nx, ny)); visited[nx][ny] = true; } } if(isTurnOn){ tmp += bfs(); } return tmp; } }
'PS' 카테고리의 다른 글
Java 1253 좋다 (0) 2023.09.11 Java 1654 랜선 자르기 (0) 2023.08.29 Java 1655 가운데를 말해요 (0) 2023.08.25 Java 2636 치즈 (0) 2023.08.22 Java 1976 여행 가자 (0) 2023.08.11