Skip to content

[서인] 9-8. 섬나라 아일랜드(BFS) #254

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 19, 2024

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

✔ 문제 유형: BFS

✔ 문제 풀이 날짜:

💡 문제 분석 요약

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

💡 알고리즘 설계

  • 방향 설정이랑 이차원 배열을 순회하며 좌표가 1일 때 answer에 1을 더하는 것은 DFS 방식과 같다.
  • queue를 만들고, 현재 좌표를 queue에서 제거하면서 그 주변을 탐색해 방문 처리를 한다.

💡코드

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 BFS(x, y) {
    let queue = [[x, y]];
    board[x][y] = 0;

    while (queue.length) {
      let [cx, cy] = queue.shift();
  
      for (const [dx, dy] of directions) {
        const nx = cx + dx;
        const ny = cy + dy;

        if (nx >= 0 && nx < n && ny >= 0 && ny < n && board[nx][ny] === 1) {
          board[nx][ny] = 0;
          queue.push([nx, ny]);
        }
      }
    }
  }

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

  return answer;
}

💡 시간복잡도

O(n^2)

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

// 다른 풀이를 작성해주세요 !

💡 느낀 점 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.

좋아요~ 🌰

무조건 할 수 있어요.
어제도 오늘도 내일도 파이팅! 🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉🏃‍♀️🎉

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.

2 participants