[Python] 백준 #4963- 섬의 개수

2023. 9. 7. 16:01·코딩테스트/백준[Python]

문제


 

 

4963번: 섬의 개수

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도

www.acmicpc.net

코드


My answer

import sys
from collections import deque
input= sys.stdin.readline

direct=[[1,0],[-1,0],[0,1],[0,-1],[1,-1],[1,1],[-1,-1],[-1,1]]

def bfs(x,y):
        Q=deque()
        Q.append((x,y))
        visit[x][y]=1
        
        while Q:
            x,y=Q.popleft()
            for i in range(8):
                n_x,n_y=x+direct[i][0],y+direct[i][1]
                if(0<=n_x<h and 0<=n_y<w):
                    if(visit[n_x][n_y]==0 and graph[n_x][n_y]==1):
                        visit[n_x][n_y]=1
                        Q.append((n_x,n_y))  
        return 0

while(1):
    w,h=map(int,input().split())
    if(w==0 and h==0):
        break
    graph=[list(map(int,input().split())) for _ in range(h)]
    visit=[[0]*w for _ in range(h)]
    cnt=0
    for i in range(h):
        for j in range(w):
            if(graph[i][j]==1 and visit[i][j]==0):
                    bfs(i,j)
                    cnt+=1
    print(cnt)

 

Another answer

import sys
sys.setrecursionlimit(10**6)

dr = [-1, -1, -1, 0, 0, 1, 1, 1]
dc = [-1, 0, 1, -1, 1, -1, 0, 1]

def dfs(a, b):
    global island, visited
    visited[a][b] = 1
    for dir in range(8):
        nr = dr[dir] + a
        nc = dc[dir] + b
        if nr >= 0 and nr < h and nc >= 0 and nc < w:
            if arr[nr][nc] == 1 and visited[nr][nc] == 0:
                dfs(nr,nc)

while True:
    island = 0
    w, h = map(int,input().split())
    if w == 0 and h == 0 :
        break
    arr = []
    visited = [[0] * w for _ in range(h)]
    for i in range(h):
        arr.append(list(map(int,input().split())))
    for i in range(h):
        for j in range(w):
            if arr[i][j] == 1 and visited[i][j] == 0:
                dfs(i,j)
                island += 1
    print(island)

풀이


이 문제도 전형적인 dfs, bfs문제로 그냥 1인 되어있는 블럭들을 방문하는 문젠데 다른 문제와 다른게 대각선도 가능하다는 것이다. 따라서 대각선만 고려해주면 쉽다. 그리고 w랑 h 헷갈리지말기 

728x90

'코딩테스트 > 백준[Python]' 카테고리의 다른 글

[Python] 백준 #2668- 숫자고르기  (0) 2023.09.08
[Python] 백준 #10026- 적록색약  (2) 2023.09.07
[Python] 백준 #2667- 단지번호붙이기  (0) 2023.09.07
[Python] 백준 #2178- 미로 탐색  (0) 2023.09.07
[Python] 백준 #1012- 유기농 배추  (0) 2023.09.05
'코딩테스트/백준[Python]' 카테고리의 다른 글
  • [Python] 백준 #2668- 숫자고르기
  • [Python] 백준 #10026- 적록색약
  • [Python] 백준 #2667- 단지번호붙이기
  • [Python] 백준 #2178- 미로 탐색
창빵맨
창빵맨
  • 창빵맨
    Let's be Developers
    창빵맨
    로그인/로그아웃
  • 전체
    오늘
    어제
    • 분류 전체보기 (481)
      • 알쓸신잡 (88)
      • ML & DL (85)
        • Computer v.. (22)
        • NLP (22)
        • 파이썬 머신러닝 완.. (3)
        • 개념정리 (38)
      • 리눅스 (21)
      • 프로젝트 (29)
        • 산불 발생 예측 (6)
        • 음성비서 (12)
        • pdf 병합 프로그.. (0)
        • 수위 예측 (5)
        • 가짜 뉴스 분류 (5)
        • 전력사용량 예측 (1)
      • 코딩테스트 (217)
        • 프로그래머스[Pyt.. (17)
        • 프로그래머스[Fai.. (3)
        • 백준[Python] (160)
        • 이것이취업을위한코딩.. (18)
        • 파이썬 알고리즘 (19)
      • 데이터분석실습 (25)
        • 데이터 과학 기반의.. (18)
        • 헬로 데이터 과학 (7)
      • 메모장 (0)
      • 잡담 (4)
  • Blog

    • 🏠 Home

    ✏️글쓰기
    💻 관리

    Personal

    GITHUB
    Instagram
  • 공지사항

  • 인기 글

  • 태그

    이분탐색
    파이썬
    그리디
    나동빈
    백준
    DFS
    이코테
    BFS
    이것이취업을위한코딩테스트다
    dp
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
상단으로

티스토리툴바