Publish:

ํƒœ๊ทธ: , , , , ,

์นดํ…Œ๊ณ ๋ฆฌ:

img_3.png

๋ฌธ์ œ

๋ฌธ์ œ ๋งํฌ

img_3.png

์„ค๋ช…

์ฃผ์–ด์ง„ ๋Œ๋‹ค๋ฆฌ ๊ฐฏ์ˆ˜(n) ๊ฐ€ ์ฃผ์–ด์ง€๊ณ  ๊ฐ ๋Œ๋‹ค๋ฆฌ์— ์ด๋™ ๊ฐ’์ด ์ ํ˜€ ์žˆ๋‹ค. ๊ทธ ๊ฐ’๋งŒํผ ์™ผ์ชฝ ๋˜๋Š” ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ ํ”„ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฐฐ์—ด์— ์ด๋™๊ฐ’์„ ๋ณด๊ด€ํ–ˆ๋‹ค๊ฐ€ ์ด๋™ ์‹œ ๊ณ„์‚ฐํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, arr[i] = x ๋ผ๋ฉด

  • i์—์„œ i - x๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด, ์™ผ์ชฝ์œผ๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๊ณ , ์ •์  i์™€ ์ •์  i - x๊ฐ€ ๊ฐ„์„ ์œผ๋กœ ์—ฐ๊ฒฐ๋œ ๊ฒƒ์ด๋‹ค.
  • i์—์„œ i + x๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด, ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๊ณ , ์ •์  i์™€ ์ •์  i + x๊ฐ€ ๊ฐ„์„ ์œผ๋กœ ์—ฐ๊ฒฐ๋œ ๊ฒƒ์ด๋‹ค.

ํ’€์ด

dfs ๋ฅผ ์‹œ์ž‘ํ•  ์ง€์ ์ด ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด์˜ค๊ณ  ํ•ด๋‹น ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ์„ ํƒ์ƒ‰ํ•œ๋‹ค. ์ด๋•Œ, ์ด๋™ ํ›„ ์ธ๋ฑ์Šค๊ฐ€ ๋ฐฐ์—ด ๋ฒ”์œ„๋‚ด์— ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋ฉด์„œ ์ง„ํ–‰ํ•œ๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Main {
  static int[] arr;
  static int count = 0;
  static int n;
  static boolean[] visited;

  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    n = Integer.parseInt(br.readLine());
    arr = new int[n];
    visited = new boolean[n];

    StringTokenizer st = new StringTokenizer(br.readLine());
    for (int i = 0; i < n; i++) {
      arr[i] = Integer.parseInt(st.nextToken());
    }

    int s = Integer.parseInt(br.readLine());
    dfs(s - 1);

    System.out.println(count);
  }

  private static void dfs(int index) {
    if (visited[index]) {
      return;
    }
    visited[index] = true;
    count++;
    int left = index - arr[index];
    int right = index + arr[index];

    if (isInRange(left)) {
      dfs(left);
    }
    if (isInRange(right)) {
      dfs(right);
    }
  }

  private static boolean isInRange(int index) {
    return index >= 0 && index < n;
  }
}
๋ฐฉ๋ฌธํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋Œ“๊ธ€,์ง€์ ,ํ”ผ๋“œ๋ฐฑ ์–ธ์ œ๋‚˜ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค๐Ÿ˜Š

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ