LeetCode 286. 牆與門 多源BFS和DFS

 思路1: DFS,對於每個門進行一次DFS搜索,記錄每個位置對每個門的距離,當有更小距離的門時更新這個數值

    public void WallsAndGates(int[][] rooms) {
        
        for (int i = 0; i < rooms.GetLength(0); i++)
        {
            for (int j = 0; j < rooms[i].GetLength(0); j++)
            {
                if (rooms[i][j] == 0)
                {
                    DFS(rooms, i, j, 0);
                }
            }
        }        
    }

    void DFS(int[][] rooms, int x, int y, int val)
    {
        if (x < 0 || x >= rooms.GetLength(0))
            return;
        if (y < 0 || y >= rooms[x].GetLength(0))
            return;
        if (rooms[x][y] < val)
            return;
        rooms[x][y] = val;
        
        DFS(rooms, x + 1, y, val + 1);
        DFS(rooms, x, y + 1, val + 1);
        DFS(rooms, x - 1, y, val + 1);
        DFS(rooms, x, y - 1, val + 1);
    }

 思路2: 多源BFS,先把每個門都壓入隊列中,然後進行BFS搜索,BFS搜索保證了每個位置只需要遍歷到一次,第一次搜索到時一定是最短距離,因此這種算法對於大量數據時肯定會更優秀

private List<int[]> directions = new List<int[]>(){new int[]{1, 0}, new int[]{-1, 0},new int[]{0, 1},new int[]{0, -1}};
private const int INF = 2147483647;
public void WallsAndGates(int[][] rooms)
    {
        Queue<int[]> queue = new Queue<int[]>();
        int maxRow = rooms.GetLength(0);
        if(maxRow == 0)
            return;
        int maxCow = rooms[0].Length;
        for (int i = 0; i < maxRow; i++)
        {
            for (int j = 0; j < maxCow; j++)
            {
                if (rooms[i][j] == 0)
                {
                    queue.Enqueue(new int[]{i,j});
                }
            }
        }
        while(queue.Count > 0)
        {
            int[] tile = queue.Dequeue();
            for(int i = 0; i < directions.Count; i++)
            {
                int x = tile[0] + directions[i][0];
                int y = tile[1] + directions[i][1];
                if(x < 0 || x > maxRow - 1 ||  y < 0 || y > maxCow - 1 || rooms[x][y] != INF)
                {
                    continue;
                }
                rooms[x][y] = rooms[tile[0]][tile[1]] + 1;
                queue.Enqueue(new int[]{x, y});
            }
        }     
    }
}

判題的結果是兩者時間差不多太多,都在340ms左右,但是明顯在數據量大的情況下應該是多源BFS算法更優秀很多。多源BFS最快是328ms,第一次的704ms是因爲用了List沒有Queue

1586571619(1).png

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章