上岸核心算法题
  • Catalog
  • 基础题
  • 核心算法200题
    • Sort Algorithms
      • MergeSort
      • Merge Two Sorted Array
      • QuickSort
      • Sort Integers II
      • Partition Array
      • N Car Fleet
      • Reverse Pairs
      • Sort Colors
      • Sort Colors II
      • Subarray Sum closest
      • Merge k Sorted Lists
      • Sort List
    • Binary Search
      • Last Position of Target
      • Positive Product
      • Guess Number Higher or Lower
      • Find Minimum in Rotated Sorted Array
      • Find Minimum in Rotated Sorted Array II
      • Kth Smallest Element in a Sorted Matrix
      • Search a 2D Matrix
      • Maximum Number in Mountain Sequence
      • Find K Closest Elements
      • Search in a Big Sorted Array
      • Fast Power
      • Find Peak Element
      • First Bad Version
      • Search in Rotated Sorted Array
      • add two numbers II
    • LinkedList
      • Reverse Linked List
      • Remove Duplicates from Sorted List
      • Remove Duplicates from Sorted List
      • Merge Two Sorted List
      • Intersection of Two Linked Lists
      • Add Two Numbers
    • List & Queue & Stack
      • Min Stack
      • Evaluate Reverse Polish Notation
      • Convert Expression to Reverse Polish Notation
    • Hashmap & Heap
      • Kth Largest Element in an Array
      • Missing Number
      • Ugly Number II
      • Implement Queue by Two Stack
      • Merge K Sorted Lists
      • Top k Largest Numbers
      • K Closest Points
      • Insert Delete GetRandom O(1)
      • First Unique Character in a String
      • Implement Stack by Two Queues
      • Moving Average from Data Stream
    • Two Pointers
      • Remove duplicates from adjacent/sorted array
      • Reverse String
      • Reverse String II
      • Reverse Words in a String
      • String shift/rotate
      • Reverse Words in a String III
      • Implement strStr()
      • Palindrome Number
      • Valid Palindrome
      • Valid Anagram
      • Kth Largest Element
      • Partition Array
      • 3Sum
      • Sort Colors II
      • Two Sum II - Input array is sorted
      • Sort Integers II
      • Remove Duplicate Numbers in Array
      • Move Zeroes
      • Two Sum III - Data structure design
      • Middle of Linked List
    • BIT Operation & Math
      • Single Number
    • Data Structure
      • First Unique Number in Data Stream
      • Sliding Window
      • Animal Shelter
      • Linked List Cycle II
      • Convert Expression to Reverse Polish Notation
      • Expression Tree Build
    • Binary Tree Divide & Conquer
      • Binary Search Tree Iterator
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Symmetric Tree
      • Invert Binary Tree
      • Search Range in Binary Search Tree
      • Largest BST Subtree
      • Lowest Common Ancestor of a Binary Search Tree
      • Lowest Common Ancestor of a Binary Tree
      • BST Node Distance
      • Maximum Width if Binary Tree
      • Construct Binary Tree from Preorder and Inorder Traversal
      • Maximum Depth of Binary Tree
      • Closest Binary Search Tree Value
      • Closest Binary Search Tree Value II
      • Validate Binary Search Tree
      • Lowest Common Ancestor III
      • Kth Smallest Element in a BST
      • Balanced Binary Tree
      • Flatten Binary Tree to Linked List
      • Binary Tree Paths
      • Minimum Subtree
      • Vertical Order Traversal of a Binary Tree
    • BFS
      • Binary Tree
        • Check full binary tree
        • Serialize and Deserialize Binary Tree
        • Graph Valid Tree
        • Check Completeness of a Binary Tree
        • Binary Tree Zigzag Level Order Traversal
        • Binary Tree Level Order Traversal
      • Graph
        • Word Ladder
        • Connected Component in Undirected Graph
        • Open the Lock
        • Clone Graph
        • Search Graph Nodes
        • Course Schedule II
        • Course Schedule
        • Topological Sorting
        • Binary Tree Maximum Path Sum II
        • Shortest Distance from All Buildings
        • Shortest Path in Undirected Graph
        • 八数码问题 Sliding Puzzle II
        • Pacific Atlantic Water Flow
      • Matrix
        • Sequence Reconstruction
        • Knight Shortest Path
        • Knight Shortest Path II
        • Number of Islands
        • Walls and Gates
        • Surrounded Regions
        • Zombie in Matrix
        • Build Post Office II
    • DFS
      • 组合型DFS
        • Letter Combinations of a Phone Number
        • Palindrome Partitioning
        • Split String
        • Generate Parentheses
        • k Sum II
        • Combination Sum IV
        • Combination Sum III
        • Combination Sum II
        • Combination Sum
        • Subsets II
        • Subsets
      • 排列型DFS
        • Permutations
        • Permutations II
        • N-Queens
        • Robot Room Cleaner
      • 剪枝优化
        • Word Pattern II
        • Word Ladder II
    • Memorization search & Dynamic Programming
      • Regular Expression Matching
      • Wildcard Matching
      • Word Break II
      • Word Break
      • Triangle
      • Word Break III
    • Basic Dynamic Programming & Coordinate Dynamic Programming
      • Backpack Problem
        • Backpack
        • Backpack V
        • Backpack II
        • Combination Sum IV (Backpack VI
        • Decode Ways
        • Decode Ways II
      • Coordinate Dynamic Programming
        • Sparse Matrix Multiplication
        • Maximum Submatrix
        • Knight Shortest Path
        • Unique Paths II
        • Unique Paths
        • Minimum Path Sum
        • knight Shortest Path II
        • Distinct Subsequences
        • Paint House
      • Sequential Dynamic Programmin
        • Triangle
        • Longest Increasing Subsequence
        • Number of Longest Increasing Subsequenc
        • Jump Game
        • Jump Game II
        • Best Time to buy and sell
        • Best Time to buy and sell II
      • Median of two Sorted Arrays
      • Median of K Sorted Arrays
      • Merge K Sorted Arrays
      • Merge K Sorted Interval Lists
      • Range Sum Query - Mutable
      • Maximum Subarray
      • Merge Sorted Array
      • Subarray Sum
      • Intersection of Two Arrays
      • Merge Two Sorted Interval Lists
      • Russian Doll Envelopes
      • Largest Divisible Subset
      • Climbing Stairs
    • Other kinds of Problems
      • LRU
      • Longest Palindromic Substring
      • Valid Palindrome
      • Implement strStr()
      • Longest Palindrome
  • 进阶算法200题
由 GitBook 提供支持
在本页

这有帮助吗?

  1. 核心算法200题
  2. BFS
  3. Matrix

Number of Islands

  • BFS

class Coordinate {
    int x, y;
    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Solution {
    /**
     * @param grid a boolean 2D matrix
     * @return an integer
     */
    public int numIslands(boolean[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        
        int n = grid.length;
        int m = grid[0].length;
        int islands = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j]) {
                    markByBFS(grid, i, j);
                    islands++;
                }
            }
        }
        
        return islands;
    }
    
    private void markByBFS(boolean[][] grid, int x, int y) {
        // magic numbers!
        int[] directionX = {0, 1, -1, 0};
        int[] directionY = {1, 0, 0, -1};
        
        Queue<Coordinate> queue = new LinkedList<>();
        
        queue.offer(new Coordinate(x, y));
        grid[x][y] = false;
        
        while (!queue.isEmpty()) {
            Coordinate coor = queue.poll();
            for (int i = 0; i < 4; i++) {
                Coordinate adj = new Coordinate(
                    coor.x + directionX[i],
                    coor.y + directionY[i]
                );
                if (!inBound(adj, grid)) {
                    continue;
                }
                if (grid[adj.x][adj.y]) {
                    grid[adj.x][adj.y] = false;
                    queue.offer(adj);
                }
            }
        }
    }
    
    private boolean inBound(Coordinate coor, boolean[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        
        return coor.x >= 0 && coor.x < n && coor.y >= 0 && coor.y < m;
    }
}
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid or not grid[0]:
            return 0
        
        directions = [[1,0],[-1,0],[0,1],[0,-1]]
        dq = collections.deque([])
        count = 0
        row, col = len(grid), len(grid[0])
        
        for i in range(row):
            for j in range(col):
                if grid[i][j] == '1':
                    count += 1
                    grid[i][j] == '0'
                    dq.append([i,j])
                    while len(dq):
                        x,y = dq.popleft()
                        for dirc in directions:
                            new_x, new_y = x+dirc[0], y+dirc[1]
                            if new_x >= 0 and new_x < row and new_y >= 0 and new_y < col and grid[new_x][new_y] == '1':
                                grid[new_x][new_y] = '0'
                                dq.append([new_x, new_y])         
                    
        return count
  • Union Find

public class Solution {
    int[] father;
    /**
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
    public int numIslands(boolean[][] grid) {
        if (grid.length == 0) {
            return 0;
        }
        int[] xBias = new int[] {0, 0, -1, 1};
        int[] yBias = new int[] {-1, 1, 0, 0};
        father = new int[grid.length * grid[0].length];
        Arrays.fill(father, -1);
        
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0});
        father[0] = grid[0][0] ? 0 : -2;
        
        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            for (int i = 0; i < xBias.length; i++) {
                int newX = current[0] + xBias[i];
                int newY = current[1] + yBias[i];
                if (!isValid(grid, newX, newY)) {
                    continue;
                }
                int oneDPoint = convert2dTo1d(newX, newY, grid[0].length);
                if (father[oneDPoint] == -1) {
                    father[oneDPoint] = -2;
                    queue.offer(new int[] {newX, newY});
                }
                if (grid[newX][newY]) {
                    if (father[oneDPoint] < 0) {
                        father[oneDPoint] = oneDPoint;
                    }
                    if (grid[current[0]][current[1]]) {
                        connect(convert2dTo1d(current[0], current[1], grid[0].length), oneDPoint);
                    }
                }
            }
        }
        
        int result = 0;
        for (int i = 0; i < father.length; i++) {
            if (father[i] == i) {
                result++;
            }
        }
        return result;
    }
    
    private boolean isValid(boolean[][] grid, int newX, int newY) {
        return newX >= 0 && newY >= 0 && newX < grid.length && newY < grid[0].length;
    }
    
    private int convert2dTo1d(int x, int y, int colLength) {
        return x * colLength + y;
    }
    
    private void connect(int a, int b) {
        int rootA = find(a);
        int rootB = find(b);
        if (rootA != rootB) {
            father[rootA] = rootB;
        }
    }
    
    private int find(int x) {
        if (father[x] == x) {
            return x;
        }
        return father[x] = find(father[x]);
    }
}
class UnionFind(object):
    def __init__(self, grid):
        row, col = len(grid), len(grid[0])
        self.parent = ['w'] * (row * col)
        self.count = 0

        for r in range(row):
            for c in range(col):
                if grid[r][c] == '1':
                    self.parent[(col * r) + c] = -1
    
    def find(self, index):
        if self.parent[index] == 'w':
            return index
        
        if self.parent[index] > -1:
            self.parent[index] = self.find(self.parent[index])
            return self.parent[index]
        
        return index
    
    def union(self, vertexA, vertexB):
        aIndex = self.find(vertexA)
        bIndex = self.find(vertexB)

        if aIndex == bIndex or self.isWater(aIndex, bIndex):
            return
        
        if self.parent[aIndex] > self.parent[bIndex]:
            self.parent[bIndex] += self.parent[aIndex]
            self.parent[aIndex] = bIndex
        else:
            self.parent[aIndex] += self.parent[bIndex]
            self.parent[bIndex] = aIndex
    
    def isWater(self, aIndex, bIndex):
        return self.parent[aIndex] == 'w' or self.parent[bIndex] == 'w'
		
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid:
            return 0
        
        row, col = len(grid), len(grid[0])
        uf = UnionFind(grid)

        for r in range(row):
            for c in range(col):
                
                if grid[r][c] is '1':
                    parentIndex = (col * r) + c

                    # right
                    if c < col - 1:
                        right = parentIndex + 1
                        uf.union(parentIndex, right)
                    
                    # down
                    if r < row - 1:
                        down = (col * (r+1)) + c
                        uf.union(parentIndex, down)
        
        islands = 0
        for ele in uf.parent:
            if ele is not 'w' and ele < 0:
                islands +=1

        return islands
上一页Knight Shortest Path II下一页Walls and Gates

最后更新于5年前

这有帮助吗?