当前位置:网站首页>Leetcode solution - number of islands
Leetcode solution - number of islands
2022-07-05 07:34:00 【Front end watermelon brother_】
Hello everyone , I'm brother watermelon , Today we will do a classic algorithm problem —— Number of Islands .
LeetCode The corresponding title on is 200 topic :https://leetcode-cn.com/problems/number-of-islands/
This problem belongs to the island problem , There is a fixed routine , That's it Flood fill Algorithm .
Flood fill Algorithm
Flood fill Algorithm is a special algorithm , It's in an area , Spread outward from a certain point and find all the points connected with it , Finally get a block .
The process of covering the whole area from one point , Because it is much like the process of flooding an island , So it was named Flood fill, Literal translation “ Flood filling ”.
The obtained area is often used to fill with new colors . Paint bucket of drawing tool 、 Magic wand tools , It's really just through Flood fill algorithmic .
Implementation is usually DFS ( Depth-first traversal ) or BFS( Breadth first traversal ).
Ideas and Implementation
Let's see how to use Flood fill Algorithm to solve this problem .
First we traverse grid Two dimensional array , When the array element is found to be ‘1’, On behalf of us, we visited part of the island , let me put it another way , We found an island , Counter count Add one .
then , We flooded the island , In doing so, all parts of the island are marked “ Visited ”. You can also use an extra size and grid Same visited Array to mark , But it is not necessary to , Unless it is not allowed to modify the original array .
After submergence , We continue to traverse from the original place , Until the end .
DFS The specific code of is implemented as :
function numIslands(grid: string[][]): number {
const m = grid.length;
const n = grid[0].length;
let count = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '1') {
// Discover part of the island
count++;
floodFill(grid, i, j);
}
}
}
return count;
};
function floodFill(grid: string[][], i: number, j: number) {
const m = grid.length; // common m That's ok
const n = grid[0].length; // common n Column
if (i < 0 || i >= m || j < 0 || j >= n) return; // Ran out of the map
if (grid[i][j] === '0') return; // Reached the edge of the island
grid[i][j] = '0'; // Flood
floodFill(grid, i - 1, j);
floodFill(grid, i + 1, j);
floodFill(grid, i, j - 1);
floodFill(grid, i, j + 1);
}
DFS There is a fatal problem : When the two-dimensional array is large , There is a risk of stack overflow .
So we might as well implement a BFS Solution method :
function numIslands(grid: string[][]): number {
const m = grid.length;
const n = grid[0].length;
let count = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '1') {
// Discover part of the island
count++;
floodFill(grid, i, j);
}
}
}
return count;
};
function floodFill(grid: string[][], i: number, j: number) {
grid[i][j] = '0';
const queue: number[][] = [[i, j]];
while (queue.length) {
const size = queue.length;
for (let k = 0; k < size; k++) {
const [i, j] = queue.shift();
fillIfInArea(grid, i - 1, j, queue);
fillIfInArea(grid, i + 1, j, queue);
fillIfInArea(grid, i, j - 1, queue);
fillIfInArea(grid, i, j + 1, queue);
}
}
}
function fillIfInArea(grid: string[][], i: number, j: number, queue: number[][]) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return;
if (grid[i][j] === '0') return;
grid[i][j] = '0';
queue.push([i, j]);
}
because JavaScript Native does not provide queues , I'm trying to save trouble , Directly use dynamic array to realize queue , The efficiency of leaving the team is very poor .
Use linked list to implement queue , The performance will be better . If you are interested in implementing a double linked list first , Then implement the queue .
ending
During the interview, I saw the algorithm problems related to the island , Be sure to remember what this article introduces “ Submerged by water , At a loss ” Of Flood fill Algorithm .
边栏推荐
- Differences between pycharm and idle and process -- join() in vs Code
- Implementation of one-dimensional convolutional neural network CNN based on FPGA (VIII) implementation of activation layer
- [MySQL] database knowledge record
- Hdu1231 maximum continuous subsequence (divide and conquer or dynamic gauge or double pointer)
- Import CV2, prompt importerror: libcblas so. 3: cannot open shared object file: No such file or directory
- [idea] common shortcut keys
- Ggplot2 drawing learning notes in R
- The problem of configuring opencv in qt5.13.2 is solved in detail
- Machine learning Seaborn visualization
- ModuleNotFoundError: No module named ‘picamera‘
猜你喜欢
M2DGR 多源多场景 地面机器人SLAM数据集
Hdu1232 unimpeded project (and collection)
Idea to view the source code of jar package and some shortcut keys (necessary for reading the source code)
Close of office 365 reading
[vscode] prohibit the pylance plug-in from automatically adding import
DataGrid offline installation of database driver
How to delete the virus of inserting USB flash disk copy of shortcut to
Target detection series - detailed explanation of the principle of fast r-cnn
Pytorch has been installed in anaconda, and pycharm normally runs code, but vs code displays no module named 'torch‘
Rough notes of C language (1)
随机推荐
Database SQL practice 4. Find the last of employees in all assigned departments_ Name and first_ name
Apple terminal skills
Daily Practice:Codeforces Round #794 (Div. 2)(A~D)
M2dgr slam data set of multi-source and multi scene ground robot
Play with grpc - go deep into concepts and principles
并查集理论讲解和代码实现
What is sodium hydroxide?
NPM and package common commands
Solve tensorfow GPU modulenotfounderror: no module named 'tensorflow_ core. estimator‘
Readme, self study record
Import CV2, prompt importerror: libcblas so. 3: cannot open shared object file: No such file or directory
苏打粉是什么?
Typescript get timestamp
Database SQL practice 3. Find the current salary details of the current leaders of each department and their corresponding department number Dept_ no
The mutual realization of C L stack and queue in I
借助 Navicat for MySQL 软件 把 不同或者相同数据库链接中的某数据库表数据 复制到 另一个数据库表中
Pit record of Chmod 2 options in deepin
Deepin, help ('command ') output saved to file
Idea push project to code cloud
Today, share the wonderful and beautiful theme of idea + website address