32. 섬의 개수
https://leetcode.com/problems/top-k-frequent-elements/
Top K Frequent Elements - LeetCode
Can you solve this real interview question? Top K Frequent Elements - Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
leetcode.com
📌문제
1을 육지로 0을 물로 가정한 2D 그리드 맵이 주어졌을 때, 섬의 개수를 계산해라.
- 예제1
📝입력
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
💻출력
Output: 1
📌풀이
3ms, 51.1mb
public class Solution {
public int numIslands(char[][] grid) {
int answer = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[i].length; j++){
if(grid[i][j] == '1'){
answer++;
dfs(grid, i, j);
}
}
}
return answer;
}
public void dfs(char[][] map, int y, int x){
if(x < 0 || y < 0 || x >= map[0].length || y >= map.length || map[y][x] == '0') return;
map[y][x] = '0';
dfs(map, y, x + 1);
dfs(map, y, x - 1);
dfs(map, y + 1, x);
dfs(map, y - 1, x);
}
}
저번주 풀이는 시간이 너무 오래 걸리는 편이라 리팩토링해달라는 스터디원의 의견에 새로 다시 짜왔다.
'Algorithm > PTUStudy' 카테고리의 다른 글
15주차. 단어 길이 재기 (0) | 2023.05.12 |
---|---|
15주차. 그래프(전화번호 문자 조합) (0) | 2023.05.12 |
14주차. 문자열 분석 (0) | 2023.05.05 |
14주차. 알파벳 찾기 (0) | 2023.05.05 |
14주차. 그래프(섬의 개수) (0) | 2023.05.05 |
32. 섬의 개수
https://leetcode.com/problems/top-k-frequent-elements/
Top K Frequent Elements - LeetCode
Can you solve this real interview question? Top K Frequent Elements - Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
leetcode.com
📌문제
1을 육지로 0을 물로 가정한 2D 그리드 맵이 주어졌을 때, 섬의 개수를 계산해라.
- 예제1
📝입력
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
💻출력
Output: 1
📌풀이
3ms, 51.1mb
public class Solution {
public int numIslands(char[][] grid) {
int answer = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[i].length; j++){
if(grid[i][j] == '1'){
answer++;
dfs(grid, i, j);
}
}
}
return answer;
}
public void dfs(char[][] map, int y, int x){
if(x < 0 || y < 0 || x >= map[0].length || y >= map.length || map[y][x] == '0') return;
map[y][x] = '0';
dfs(map, y, x + 1);
dfs(map, y, x - 1);
dfs(map, y + 1, x);
dfs(map, y - 1, x);
}
}
저번주 풀이는 시간이 너무 오래 걸리는 편이라 리팩토링해달라는 스터디원의 의견에 새로 다시 짜왔다.
'Algorithm > PTUStudy' 카테고리의 다른 글
15주차. 단어 길이 재기 (0) | 2023.05.12 |
---|---|
15주차. 그래프(전화번호 문자 조합) (0) | 2023.05.12 |
14주차. 문자열 분석 (0) | 2023.05.05 |
14주차. 알파벳 찾기 (0) | 2023.05.05 |
14주차. 그래프(섬의 개수) (0) | 2023.05.05 |