Tags » Speed » Page 2

Quote of the Day | 08.07.20

Love has a speed. And it’s slower than I am. There’s a good chance it’s slower than you are. Love pauses. Love lingers. Love offers full focus and gives far more than it takes. 18 more words

What Does 50-mph Feel Like on a Bicycle?! One Word...

High speed warning: First of all, let me be very clear; purposely riding your bike above, say 10-mph, is inherently dangerous. Doing so above 20 is, as one would guess, more dangerous. 1,245 more words

Cycling

I loved playing The Need for Speed

If you’re in a group of people being chased by a bear, you only need to be faster than the slowest person in the group. But that’s not how websites work: being faster than at least one other website, or even faster than the ‘average’ website, is not a great achievement when the average website speed is frustratingly slow.

32 more words
Blog

934. Shortest BridgeMedium

首先这道题的思路是,先分别dfs出两个岛屿,并保存到两个list中,之后遍历两个list中的每一个点,求解最小的距离。小心25行的错误,一定要-1,还有36行不能大意。

真正注意的是不同的写法,导致运行速度的差异,如果按照原来注释的做法leetcode会超时,按照参考的https://leetcode.com/problems/shortest-bridge/discuss/763981/Java-DFS-easy-to-understand是896ms,按照现行的做法是406ms。

class Solution {
    boolean[][] visited;
    int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 
    
    public int shortestBridge(int[][] A) {
        int r = A.length, c = A[0].length;
        List<int[]> island1 = new LinkedList<>();
        List<int[]> island2 = new LinkedList<>();
        visited = new boolean[r][c];
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A[0].length; j++) {
                if (A[i][j] == 1 && !visited[i][j]) {
                    if (island1.size() == 0) 
                        dfs(A, i, j, island1);
                    else
                        dfs(A, i, j, island2);
                }
            }
        }
        int minPath = Integer.MAX_VALUE;
        // for (int i = 0; i < island1.size(); i++) 
        //     for (int j = 0; j < island2.size(); j++) {
        //         int[] p1 = island1.get(i);
        //         int[] p2 = island2.get(j);
        //         //minPath = Math.min(minPath, Math.abs(p2[0] - p1[0]) + Math.abs(p2[1] - p1[1]));
        //         minPath = Math.min(minPath, Math.abs(p2[0] - p1[0]) + Math.abs(p2[1] - p1[1]) - 1);
        //     }
        for (int[] p1: island1)
            for (int[] p2: island2)
                minPath = Math.min(minPath, Math.abs(p2[0] - p1[0]) + Math.abs(p2[1] - p1[1]) - 1);
        
        return minPath;
    }
    
    private void dfs(int[][] A, int x, int y, List<int[]> island) {
        //if (x < 0 || x >= A.length || y < 0 || y >= A[0].length || A[x][y] != 1)
        if (x < 0 || x >= A.length || y < 0 || y >= A[0].length || A[x][y] != 1 || visited[x][y])
            return;
        visited[x][y] = true;
        island.add(new int[]{x, y});
        for (int[] dir: dirs)
            dfs(A, x + dir[0], y + dir[1], island);
    }
}
Strive