算法细节系列(16):深度优先搜索
算法細節系列(16):深度優先搜索
詳細代碼可以fork下Github上leetcode項目,不定期更新。
題目均摘自leetcode:
1. 329 Longest Increasing Path in a Matrix
2. 488 Zuma Game
3. 417 Pacific Atlantic Water Flow
4. 332 Reconstruct Itinerary
329 Longest Increasing Path in a Matrix
Problem:
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4
The longest increasing path is [1,2,6,9]
Example 2:
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
求圖中不斷遞增的最大路徑長度,采用DFS暴力搜索,代碼如下:
public int longestIncreasingPath(int[][] matrix) {row = matrix.length;if (row == 0) return 0;col = matrix[0].length;if (col == 0) return 0;max = 0;for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {count = 1;dfs(matrix,i,j);}}return max;}static int count = 1;static int max = 0;static int row,col;static final int[][] direction = {{-1,0},{1,0},{0,-1},{0,1}};private void dfs(int[][] matrix, int cx, int cy){for (int i = 0; i < 4; i++){int nx = cx + direction[i][0];int ny = cy + direction[i][1];max = Math.max(max, count);if (nx >= 0 && nx < row && ny >=0 && ny < col && matrix[nx][ny] > matrix[cx][cy]){count++;dfs(matrix, nx, ny);//注意狀態還原count--;}}}代碼TLE了,原因很簡單,該代碼沒有記錄已經搜索完畢的路徑長度,而我們知道,從一個起點出發或許能夠抵達某個已經搜過的路徑上,所以優化代碼如下:
public int longestIncreasingPath(int[][] matrix) {int row = matrix.length;if (row == 0) return 0;int col = matrix[0].length;if (col == 0) return 0;int[][] cache = new int[row][col];int max = 1;for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {int len = dfs(matrix, i, j, row, col, cache);max = Math.max(len, max);}}return max;}final static int[][] direction = {{-1,0},{1,0},{0,-1},{0,1}};private int dfs(int[][] matrix, int i , int j, int row, int col, int[][] cache){if (cache[i][j] != 0) return cache[i][j];int max = 1;for (int[] dir : direction){int nx = i + dir[0], ny = j + dir[1];if (nx < 0 || nx >= row || ny < 0 || ny >= col || matrix[nx][ny] <= matrix[i][j]) continue;int len = 1 + dfs(matrix, nx, ny, row, col, cache);max = Math.max(max, len);}return cache[i][j] = max;}DFS帶返回值的特點,天然的能夠進行一些狀態還原,所以不需要像第一版代碼一樣,在DFS后加入count--。
488 Zuma Game
Problem:
Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.
Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.
Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.
Examples:
Input: “WRRBBW”, “RB”
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW
Input: “WWRRBBWW”, “WRBRW”
Output: 2
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty
Input:”G”, “GGGGG”
Output: 2
Explanation: G -> G[G] -> GG[G] -> empty
Input: “RBYYBBRRB”, “YRBGB”
Output: 3
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty
Note:
- You may assume that the initial row of balls on the table won’t have any 3 or more consecutive balls with the same color.
- The number of balls on the table won’t exceed 20, and the string represents these balls is called “board” in the input.
- The number of balls in your hand won’t exceed 5, and the string represents these balls is called “hand” in the input.
- Both input strings will be non-empty and only contain characters ‘R’,’Y’,’B’,’G’,’W’.
小時候玩的泡泡龍游戲,遇到三個以上顏色相同的球就消除,直到為空。
思路:
明確搜索對象,此處對象有兩個【手中的球】和【桌上的球】,此處以桌上的球為遍歷對象,因為我們知道在桌上,出現的球總共就兩種情況,每種顏色要么只出現一次,要么只出現連續兩次,只要手中的球足以填補成三個,我們就進行消除。遍歷所有情況求得一個最小的步數,即為答案。代碼如下:
注意一些細節,因為順序無關,所以我們可以直接用一個map進行計數。防止特殊情況j == s.length(),所以在board后多了一個字符'#'。removeConsecutive()該方法針對單獨連續的字符串www將返回www而不是空串,需注意。對連續的相同字符串計數的代碼可以研究研究,挺不錯的一個小技巧。
417 Pacific Atlantic Water Flow
Problem:
Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the “Pacific ocean” touches the left and top edges of the matrix and the “Atlantic ocean” touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
- The order of returned grid coordinates does not matter.
- Both m and n are less than 150.
Example:
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
思路:
可以沿著山峰順流而下,但得保證每次下降都是流向更低的地方,如果算法不滿足,就會出錯。在實際編寫代碼時,發現這種想法較難實現,于是用了一種逆流而上的做法,分別從大西洋和太平洋出發,尋找更高的山峰,只增不減。這樣,如果太平洋和大西洋都能抵達某個山峰,該山峰就是我們所求的解。代碼如下:
332 Reconstruct Itinerary
Problem:
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
- If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary [“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”].
- All airports are represented by three capital letters (IATA code).
- You may assume all tickets form at least one valid itinerary.
Example 1:
tickets = [[“MUC”, “LHR”], [“JFK”, “MUC”], [“SFO”, “SJC”], [“LHR”, “SFO”]]
Return [“JFK”, “MUC”, “LHR”, “SFO”, “SJC”].
Example 2:
tickets = [[“JFK”,”SFO”],[“JFK”,”ATL”],[“SFO”,”ATL”],[“ATL”,”JFK”],[“ATL”,”SFO”]]
Return [“JFK”,”ATL”,”JFK”,”SFO”,”ATL”,”SFO”].
Another possible reconstruction is [“JFK”,”SFO”,”ATL”,”JFK”,”ATL”,”SFO”]. But it is larger in lexical order.
思路:
數據結構采用Map和優先隊列來建立鄰接矩陣,路徑的尋找采用貪心,所以只要DFS而不需要BFS,遍歷結束后,從底自上把答案添加到LinkedList中去,算法與數據結構的完美結合,證明暫略。代碼如下:
總結
以上是生活随笔為你收集整理的算法细节系列(16):深度优先搜索的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQLSERVER Agent服务无法启
- 下一篇: 第十一章 自动编码器