반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 개발자 취준
- BigO notation
- 프로그래머스 배열의 유사도 파이썬
- 파이썬 특정 문자 제거하기
- 가위바위보 풀이
- 스프링 시스템 구조
- 공선옥
- 비지니스 레이어
- leftJoin
- 프로그래머스
- 특정문자 제거하기
- 프로그래머스 가위바위보
- 파이썬 컬렉션
- 리트허브 커밋
- 프로그래머스 특정 문자 제거하기
- collection python
- 리트허브 사용법
- 프레젠테이션 레이어
- 알고리즘
- Programmers 배열의 유사도
- 주니어개발자
- 춥고더운우리집
- programmers 배열 회전
- 리트허브 오류
- 슈츠 자막
- 프로그래머스 배열 회전시키기
- 2-layered architecture
- 배열의 유사도 파이썬
- 프로그래머스 가위바위보 풀이
- 춥고 더운 우리 집
Archives
- Today
- Total
기억보다 기록을
[Leetcode] Number of Islands (python) , dfs 풀이 본문
반응형
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is '0' or '1'.
풀이 아이디어
- 대각선은 섬이 아니다.
- 가로세로로 연결된 모든 1을 0으로 바꾸고 카운트 변수를 증가시키자.
- dfs 함수의 베이스 케이스는, 함수가 언제 끝나는지 + 그리드 벗어나지 않게 범위 내에 있는지 체크
- 테스트 케이스를 일부만 통과하길래 왜지하고 고민했는데 dy 값 하나가 음수여서 그런 것이었다. 왜 눈에 안보였을까..ㅎ 역시 휴먼에러..
풀이
class Solution:
dx = [0,1,0,-1]
dy = [-1,0,1,0]
def numIslands(self, grid: List[List[str]]) -> int:
cnt = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1' :
self.dfs(grid,i,j)
cnt += 1
return cnt
def dfs(self, grid, i, j) :
if i<0 or i>= len(grid) or j<0 or j>= len(grid[0]) or grid[i][j] == '0':
return
grid[i][j] = '0'
for k in range(4):
self.dfs(grid, i+self.dx[k], j+self.dy[k])
추가로 풀어볼 문제 (DFS)
https://school.programmers.co.kr/learn/courses/30/lessons/42839
https://leetcode.com/problems/cousins-in-binary-tree-ii/description/
https://leetcode.com/problems/cousins-in-binary-tree/
출처:
반응형
'Algorithm > Leet code' 카테고리의 다른 글
[Leetcode] two sum을 4가지 방법으로 풀어보기 (python) (0) | 2023.04.27 |
---|---|
[Leetcode] Number of Islands (BFS 풀이) (0) | 2023.04.26 |
[leetcode] Most Common Word (0) | 2023.02.22 |
[leetcode] Reorder Data in Log Files (python) (0) | 2023.02.21 |
[leetcode] Valid Palindrome (python) (0) | 2023.02.21 |