티스토리 뷰
1. 배열 안에 섬이 몇 개인지를 찾는 문제이다.
200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count 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.
Example 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
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"] ]
Output: 3
3. 방법은
3-1 0,0 셀부터 시작하여 1인 것을 발견하면 bfs을 실행하여 연결된 그래프를 찾으면서 모두 0으로 바꾼다.
3-2 그러면 연결되지 않은 부부만 남게 된다. 2-1에서 bfs를 시작한 바로 다음 위치부터 계속 해 나간다.
3-2-1 3-1 때문에 이미 연결된 것은 0으로 바뀌었을 것이므로 1이 발견되면 다른 섬의 일부인 것이다.
import java.util.LinkedList;
import java.util.Queue;
public class App2 {
public static void main(String[] args) {
Solution1 sol = new Solution1();
// char[][] grid = {
// {'1','1','1','1','0'},
// {'1','1','0','1','0'},
// {'1','1','0','0','0'},
// {'0','0','0','0','0'}};
char[][] grid = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};
System.out.println(sol.numIslands(grid));
}
}
class Solution1 {
class Point {
public int row, col;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
public String toString() {
return "[ " + row + " , " + col + " ]";
}
}
public int numIslands(char[][] grid) {
int numOfIslands = 0;
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[0].length; j++) {
if (grid[i][j] == '1') {
System.out.println("\nStaring point [ " + i + ", " + j + " ]");
bfs(grid, new Point(i, j));
numOfIslands++;
}
}
}
return numOfIslands;
}
private void bfs(char[][] grid, Point point) {
Queue<Point> queue = new LinkedList<>();
int[][] directions = {{1,0}, {-1,0}, {0,1}, {0,-1}};
queue.add(point);
while (!queue.isEmpty()) {
int size = queue.size();
System.out.println(queue.toString());
for (int i=0; i<size; i++) {
Point position = queue.poll();
grid[position.row][position.col] = '0';
for (int[] direction : directions) {
int newRow = position.row + direction[0];
int newCol = position.col + direction[1];
if (newRow >= 0 && newRow < grid.length &&
newCol >= 0 && newCol < grid[0].length &&
grid[newRow][newCol] == '1') {
queue.add(new Point(newRow, newCol));
}
}
}
}
}
}
4. 결과 화면
'Basic > Algorithms' 카테고리의 다른 글
Questions : Partition Labels (0) | 2020.07.25 |
---|---|
Questions : Reorder Data in Log Files (0) | 2020.07.25 |
Questions : 자동완성 (0) | 2020.07.25 |
Questions : Critical Connections (0) | 2020.07.24 |
Questions : Zombie in the Matrix (0) | 2020.07.24 |
- Total
- Today
- Yesterday
- 도커 개발환경 참고
- AWS ARN 구조
- Immuability에 관한 설명
- 자바스크립트 멀티 비동기 함수 호출 참고
- WSDL 참고
- SOAP 컨슈머 참고
- MySql dump 사용법
- AWS Lambda with Addon
- NFC 드라이버 linux 설치
- electron IPC
- mifare classic 강의
- go module 관련 상세한 정보
- C 메모리 찍어보기
- C++ Addon 마이그레이션
- JAX WS Header 관련 stackoverflow
- SOAP Custom Header 설정 참고
- SOAP Custom Header
- SOAP BindingProvider
- dispatcher 사용하여 설정
- vagrant kvm으로 사용하기
- git fork, pull request to the …
- vagrant libvirt bridge network
- python, js의 async, await의 차이
- go JSON struct 생성
- Netflix Kinesis 활용 분석
- docker credential problem
- private subnet에서 outbound IP 확…
- 안드로이드 coroutine
- kotlin with, apply, also 등
- 안드로이드 초기로딩이 안되는 경우
- navigation 데이터 보내기
- 레이스 컨디션 navController
- raylib
- 로그인
- XML
- RestTemplate
- 스프링부트
- 설정
- 자바
- 스프링
- hibernate
- spring boot
- 매핑
- Security
- Validation
- login
- Angular
- Rest
- Many-To-Many
- WebMvc
- mapping
- jsp
- crud
- 상속
- form
- 하이버네이트
- 설정하기
- MYSQL
- one-to-many
- Spring
- 외부파일
- one-to-one
- Spring Security