LeetCode 1034 - Coloring A Border


https://leetcode.com/problems/coloring-a-border/
Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location.
Two squares belong to the same connected component if and only if they have the same color and are next to each other in any of the 4 directions.
The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).
Given a square at location (r0, c0) in the grid and a color, color the border of the connected component of that square with the given color, and return the final grid.

Example 1:
Input: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
Output: [[3, 3], [3, 2]]
Example 2:
Input: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
Output: [[1, 3, 3], [2, 3, 3]]
Example 3:
Input: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
Output: [[2, 2, 2], [2, 1, 2], [2, 2, 2]]

Note:
  1. 1 <= grid.length <= 50
  2. 1 <= grid[0].length <= 50
  3. 1 <= grid[i][j] <= 1000
  4. 0 <= r0 < grid.length
  5. 0 <= c0 < grid[0].length
  6. 1 <= color <= 1000
https://leetcode.com/problems/coloring-a-border/discuss/282847/C%2B%2B-with-picture-DFS
X. BFS
https://leetcode.com/problems/coloring-a-border/discuss/283262/Java-BFS-and-DFS-short-codes
  1. Let m = grid.length, n = grid[0].length, use the number
    from 0 to m * n - 1 to identify the cells to avoid duplicates;
    e.g., grid[x][y]'s cell number is x * n + y;
  2. put the initial cell [r0, c0] into the Queue then poll it out,
    then check if it is on the grid bounday;
  3. Traverse the cell's 4 neighbors:
    a) if its neighbor is of different color, the cell is on the
    component border;
    b) if same color, put the neighbor into Queue;
  4. repeat the above 2 and 3 till Queue is empty.
    private static final int[] d = { 0, 1, 0, -1, 0 }; // neighbors' relative displacements.
    public int[][] colorBorder(int[][] grid, int r0, int c0, int color) {
        int clr = grid[r0][c0], m = grid.length, n = grid[0].length;
        Set<Integer> seen = new HashSet<>(); // put the cell number into Set to avoid visiting again.
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{ r0, c0 }); // add initial cell.
        seen.add(r0 * n + c0); // add initial cell number.
        while (!q.isEmpty()) { // BFS starts.
            int r = q.peek()[0], c = q.poll()[1];
            if (r == 0 || r == m - 1 || c == 0 || c == n - 1) { grid[r][c] = color; } // on grid boundary.
            for (int i = 0; i < 4; ++i) { // travers its 4 neighbors.
                int x = r + d[i], y = c + d[i + 1]; // neighbor coordinates.
                if (x < 0 || x >= m || y < 0 || y >= n || seen.contains(x * n + y)) { continue; } // out of grid or visited already.
                if (grid[x][y] == clr) { // its neighbor is of same color.
                    seen.add(x * n + y); // avoid visiting again.
                    q.offer(new int[]{ x, y }); // put it into Queue.
                }else { // its neighbor is of different color, hence it is on component boundary. 
                    grid[r][c] = color;
                }
            }
        }
        return grid;
    }

X. DFS
Use DFS to explore the cell (r0, c0)'s component, and negate the visited cell, traverse its 4 neighbors. After the traversal, change back from the negative if the component cell is at inner part.
    private int[] d = { 0, 1, 0, -1, 0 }; // neighbors' relative displacements.
    public int[][] colorBorder(int[][] grid, int r0, int c0, int color) {
        dfs(grid, r0, c0, grid[r0][c0]);
        for (int[] g : grid) {
            for (int i = 0; i < g.length; ++i) {
                if (g[i] < 0) { g[i] = color; }
            }
        }
        return grid;
    }
    private void dfs(int[][] grid, int r, int c, int clr) {
        grid[r][c] = -clr; // mark as visited.
        int cnt = 0; // use to count grid[r][c]'s component neighbors (same color as itself).
        for (int i = 0; i < 4; ++i) { // traverse 4 neighbors.
            int x = r + d[i], y = c + d[i + 1]; // nieghbor's coordinates.
            if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || Math.abs(grid[x][y]) != clr) { continue; } // out of grid or not same component.
            ++cnt; // only if all 4 neighbors of grid[r][c] have same color as itself, it is on inner part.
            if (grid[x][y] == clr) { dfs(grid, x, y, clr); }
        }
        if (cnt == 4) { grid[r][c] = clr; } // inner part, change back.
    }
https://leetcode.com/problems/coloring-a-border/discuss/284935/Java-DFS-Easy-to-understand!
The primary intuition is to do a DFS from the starting cell and find all the cells of the oldColor that needs to be changed. We mark these cells with a negative value of the oldColor. Once this is done, we need to find out which among those cells lies interior and which lies exterior. Interior cells have all 4 neighboring cells(top, bottom, left and right) to have either the oldColor value or -oldColor value. Make these interior cells positive again. Once we have processed this for all necessary nodes from the starting cell, we will get a grid containing negative cells that denote the boundary. We need to sweep through the entire grid and change these negative values to the new color.
  • Check for existence of null or empty grid and return null if so.
  • Store the color of starting cell grid[r0][c0] in oldColor.
  • Initiate a DFS from starting cell.
  • Check if the current cell lies out of bounds off the grid or if current cell does not have the same color as starting cell and return if so.
  • Otherwise, change the current cell's color to a negative value for us to remember that we have processed this cell.
  • Do a DFS for all neighboring points that are up, down, left and right from current cell.
  • Once DFS returns back for the current cell after processing all directions from it, change the current cell's color back to positive value if you find that the current cell lies within adjacent cells top, bottom, left and right with the same value.
  • Once the entire DFS has been processed, we now have a grid containing negative values representing the border which needs to be recolored to the new color.
class Solution {
    public int[][] colorBorder(int[][] grid, int r0, int c0, int color) {
        if(grid == null || grid.length == 0)
            return null;
        int oldColor = grid[r0][c0];
        dfs(grid, r0, c0, oldColor);
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] < 0)
                    grid[i][j] = color;
            }
        }
        return grid;
    }
    public void dfs(int[][] grid, int i, int j, int oldColor) {
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != oldColor) 
            return;
        grid[i][j] = -oldColor;
        dfs(grid, i+1, j, oldColor);
        dfs(grid, i-1, j, oldColor);
        dfs(grid, i, j+1, oldColor);
        dfs(grid, i, j-1, oldColor);
        if(i > 0 && j > 0 && i < grid.length-1 && j < grid[0].length-1
           && oldColor == Math.abs(grid[i+1][j])
           && oldColor == Math.abs(grid[i-1][j])
           && oldColor == Math.abs(grid[i][j+1])
           && oldColor == Math.abs(grid[i][j-1]))
            grid[i][j] = oldColor;
    }

https://xingxingpark.com/Leetcode-1034-Coloring-A-Border/
题目给我们一个坐标,要求将这个坐标表示的点所属的component的边界用给定的颜色标记出来。
我们用DFS的方法解决这道题。从给定的起点A开始,我们可以方便的遍历A所在的component的所有点。为了不开辟额空间,我们直接将A原来的颜色originColor翻转为-originColor
那如何在找出边界呢?我们只需要在完成一个点上下左右四个方向的遍历之后,检查这个点是不是在component内部,在的话我们再次翻转-originColor,把它复原为originColor。经过这样的步骤之后,地图上所有标记为-originColor的点就是我们需要的边界了。我们将这些点重新标记为题目要求的color即可。
怎么判断一个方格是否是 The border of a connected component?有两个条件,一是这个方格处在grid的边界上,二是这个方格的上下左右四个方向的方格的颜色和自身不都一样。我的方法是分两步,第一步把和输入方格connect的所有方格都找出来,第二部就是依次判断这些connect的方格是否处于border,如果处于则修改颜色。


https://buptwc.com/2019/05/02/Leetcode-1034-Coloring-A-Border/
给定一个二维矩阵grid,矩阵中的值代表在矩阵那处位置的颜色。
相连的颜色被认为是一个连通区域。
连通区域的边界是指那些和不属于该连通区域的块相连的部分,或者是处于整个矩阵的边界处的部分。
给定一个位置(r0, c0),和一个颜色color。将(r0, c0)所在连通区域的颜色全部改成color,然后返回最终的矩阵grid.
示例 1:
输入: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
输出: [[3, 3], [3, 2]]
示例 2:
输入: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
输出: [[1, 3, 3], [2, 3, 3]]

示例 3:
输入: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
输出: [[2, 2, 2], [2, 1, 2], [2, 2, 2]]

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts