티스토리 뷰
반응형
문제
https://leetcode.com/problems/max-area-of-island/description/
Max Area of Island - LeetCode
Can you solve this real interview question? Max Area of Island - You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are su
leetcode.com
풀이 코드
class Solution {
static int max; //섬 크기의 최대값을 담을 변수
static int[][] map; //grid를 담을 변수
static int count; //각 섬의 크기를 담을 변수
//grid의 좌표 클래스
private static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
/**
* grid에서 1을 찾으면 DFS로 순회하여 섬의 크기를 구한다.
* 가장 큰 섬의 크기를 반환한다.
*/
public int maxAreaOfIsland(int[][] grid) {
int m = grid.length; //세로 길이
int n = grid[0].length; //가로 길이
max = 0; //최대값을 0으로 초기화한다.
map = grid; //static 변수에 grid를 담는다.
//반복문으로 grid 내의 1을 찾는다.
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
//1이 발견되면, count를 0으로 초기화 하고 좌표를 DFS 메소드로 넘긴다.
if (grid[i][j] == 1) {
count = 0;
DFS(new Point(i, j));
}
}
}
return max;
}
private static void DFS(Point point) {
//좌표값이 grid의 범위를 넘어가면 return한다.
if (point.x < 0 || point.y < 0 || point.x >= map.length || point.y >= map[0].length) return;
//좌표에 해당하는 값이 1이 아니면 return한다.
if (map[point.x][point.y] != 1) return;
//좌표값이 grid 범위 안에 있고, 해당하는 값이 1인 경우
map[point.x][point.y] = 2; //grid의 값을 2로 바꿔준다.
count++; //섬의 크기를 1 올린다.
max = Math.max(max, count); //가장 큰 섬 크기를 담는다.
DFS(new Point(point.x, point.y + 1)); //오른쪽 탐색
DFS(new Point(point.x + 1, point.y)); //아래 탐색
DFS(new Point(point.x, point.y - 1)); //왼쪽 탐색
DFS(new Point(point.x - 1, point.y)); //위 탐색
}
}
반응형
'코딩테스트 > LeetCode' 카테고리의 다른 글
Keys and Rooms (0) | 2023.10.12 |
---|---|
Create Binary Tree From Descriptions (0) | 2023.10.11 |
Symmetric Tree (0) | 2023.10.10 |
Two Sum IV - Input is a BST (0) | 2023.10.10 |
Count Good Nodes in Binary Tree (0) | 2023.10.06 |
반응형