Skip to content

[서인] 9-7. 섬나라 아일랜드(DFS) #250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

Seoin02
Copy link
Contributor

@Seoin02 Seoin02 commented Sep 17, 2024

✔ 문제 제목: 섬나라 아일랜드(DFS)

✔ 문제 유형: 그래프

✔ 문제 풀이 날짜: 2024.09.18

💡 문제 분석 요약

  • N*N 섬나라 아일랜드 지도가 격자판으로 주어질 때 섬이 몇 개 인지 구한다.
  • 각 섬은 1로 표시돼 상하좌우 대각선으로 연결돼있다.

💡 알고리즘 설계

  • 방향 배열을 선언한다.
  • 그래프를 순회하다가 1을 만나면 섬인 것이고, 인근 섬들을 탐색한다.
  • 그래프를 순회하다가 0을 만나면 방문하지 않게 조치한다.

💡코드

function solution(board) {
  let answer = 0;
  const n = board.length;

  const directions = [
    [-1, 0],
    [1, 0],
    [0, -1],
    [0, 1],
    [-1, -1],
    [-1, 1],
    [1, -1],
    [1, 1]
  ];

  function DFS(x, y) {

    board[x][y] = 0;

    for (const [dx, dy] of directions) {
      const nx = x + dx;
      const ny = y + dy;

      if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && board[nx][ny] === 1) {
        DFS(nx, ny);
      }
    }
  }

  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      if (board[i][j] === 1) {
        answer++;
        DFS(i, j);
      }
    }
  }

  return answer;
}

💡 시간복잡도

O(n)

💡 틀린 이유와 틀린 부분 수정 or 다른 풀이

  • 9-4 미로탐색을 참고했는데 visited를 선언하지 않아도 0으로 표기해도 되는군요.
// 다른 풀이를 작성해주세요 !

💡 느낀 점 or 기억할 정보

  • 알고리즘 설계엔 구현 내용을 적지 않는다는 코테책 말대로 흐름만 적으려고 해봤습니다.
  • 근데 코드 설명을 적는 게 나은 것 같기도 합니다ㅠㅠ

Copy link
Contributor

@devwqc devwqc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋아요~ ☕

저도 처음에 visited를 따로 선언해야 한다는 생각을 했었는데 그냥 그 지역 자체를 바다로 바꾸면 돼서 또 하나 깨닫게 됐습니다.
저는 일단 책에서 말한 의사 코드 작성해서 풀어보려구요! 👏💯👏💯👏💯👏💯👏💯👏💯👏💯👏💯👏💯👏💯👏💯👏💯👏💯👏💯

Copy link
Contributor

@ayoung-iya ayoung-iya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

책 내용을 반영해보는 서인님 멋져 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants