leetcode 934. Shortest Bridge

The algorithm for this problem is not so hard to figure out.

This is a problem of finding the length of the shortest path in graph. As I mentioned in my previous article, BFS is a good way to slove this kind of problem.

This problem is a little different, it‘s no begining point but beginning points. So before the real BFS, we should find all points in one island. Then we can begin our bfs with a queue which contains all points of one island.

It‘s marked as medium in leetcode, but the recommended solution has 81 lines. And after some inspection on discuss articles, I found that most solutions exceed 40 lines. It‘s really not easy to get AC once with that many code. So I think hard is a more accurate label for this problem.

    class Solution {
         public int shortestBridge(int[][] A) {
            int M = A.length, N = A[0].length;
            int i = 0;
            for (i = 0; i < M * N; ++i) {
                if (A[i / N][i % N] == 1) break;
            }
            Map<Integer, Integer> s = new HashMap<>();
            Queue<Integer> q = new LinkedList<>();
            q.add(i);
            s.put(i, 1);
            int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
            while (!q.isEmpty()) {
                Integer pos = q.poll();
                int x = pos / N, y = pos % N;
                for (int[] move: moves) {
                    int nx = x + move[0], ny = y + move[1];
                    if (nx >= 0 && ny >= 0 && nx < M && ny < N) {
                        int val = nx * N + ny;
                        if (s.get(val) == null && A[nx][ny] == 1) {
                            s.put(val, 1);
                            q.add(val);
                        }
                    }
                }
            }
            q.addAll(s.keySet());
            while (!q.isEmpty()) {
                Integer pos = q.poll();
                Integer mark = s.get(pos);
                int x = pos / N, y = pos % N;
                for (int[] move: moves) {
                    int nx = x + move[0], ny = y + move[1];
                    if (nx >= 0 && ny >= 0 && nx < M && ny < N) {
                        int val = nx * N + ny;
                        if (s.get(val) == null) {
                            if (A[nx][ny] == 0) {
                                s.put(val, mark + 1);
                                q.add(val);
                            }
                            else {
                                return mark - 1;
                            }
                        }
                    }
                }
            }
            return -1;
        }
    }

原文地址:https://www.cnblogs.com/exhausttolive/p/10604148.html

时间: 2024-10-14 12:19:25

leetcode 934. Shortest Bridge的相关文章

[LeetCode] 244. Shortest Word Distance II 最短单词距离 II

This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it? Design a class which receives a list

[LeetCode] 243. Shortest Word Distance 最短单词距离

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. For example,Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. G

[LeetCode][JavaScript]Shortest Palindrome

Shortest Palindrome Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", retur

Java for LeetCode 214 Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "aaacecaaa&qu

[LeetCode] 847. Shortest Path Visiting All Nodes 访问所有结点的最短路径

An undirected, connected graph of N nodes (labeled?0, 1, 2, ..., N-1) is given as?graph. graph.length = N, and?j != i?is in the list?graph[i]?exactly once, if and only if nodes?i?and?j?are connected. Return the length of the shortest path that visits

BFS 基础写法 —— 以 LeetCode #1091 Shortest Path in Binary Matrix 为例

Question In an N by N square grid, each cell is either empty (0) or blocked (1). A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that: Adjacent cells C_i and C_{i+1} are connected

LeetCode 1293. Shortest Path in a Grid with Obstacles Elimination

原题链接在这里:https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ 题目: Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell. Return

[LeetCode] 613. Shortest Distance in a Line_Easy tag: SQL

Table point holds the x coordinate of some points on x-axis in a plane, which are all integers. Write a query to find the shortest distance between two points in these points. | x | |-----| | -1 | | 0 | | 2 | The shortest distance is '1' obviously, w

LeetCode - 581. Shortest Unsorted Continuous Subarray

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. E