https://zhipianxuan.github.io/html
1、樹的DFSgit
2、二維矩陣的DFSgithub
3、圖的DFS算法
#row, col = map(int, input().split()) #graph = [] #for _ in range(row): # graph.append(list(map(int, input().split()))) #print(graph) #x1, y1, x2, y2 = map(int, input().split()) dirs = [(-1, 0), (1, 0), (0, 1), (0, -1)] M = 10 ** 9 res = [0] graph = [[0, 1, 0, 0, 0], [0, 2, 3, 0, 0], [0, 0, 4, 5, 0], [0, 0, 7, 6, 0]] row = 4 col = 5 x1, y1, x2, y2 = 0, 1, 3, 2 def dfs(x1, y1, visited): if x1 == x2 and y1 == y2: res[0] += 1 return for i, j in dirs: tmp_x = i + x1 tmp_y = j + y1 if 0 <= tmp_x < row and 0 <= tmp_y < col and graph[tmp_x][tmp_y] > graph[x1][y1] \ and (tmp_x, tmp_y) not in visited: dfs(tmp_x, tmp_y, visited | {(tmp_x, tmp_y)}) dfs(x1, y1, {(x1, y1)}) print(res[0] % M)
給定一個包含了一些 0 和 1的非空二維數組 grid
, 一個 島嶼 是由四個方向 (水平或垂直) 的 1
(表明土地) 構成的組合。你能夠假設二維矩陣的四個邊緣都被水包圍着。數組
找到給定的二維數組中最大的島嶼面積。(若是沒有島嶼,則返回面積爲0。)app
示例 1:post
[[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]]
對於上面這個給定矩陣應返回 6
。注意答案不該該是11,由於島嶼只能包含水平或垂直的四個方向的‘1’。url
示例 2:spa
[[0,0,0,0,0,0,0,0]]
對於上面這個給定的矩陣, 返回 0
。code
注意: 給定的矩陣grid
的長度和寬度都不超過 50。
遍歷矩陣,遇到 grid [i] [j] = 1時,就算值【採用dfs來算】
dfs : 先將grid [i] [j] 置0,而後再 return 1 + dfs [i-1] [j] + dfs [i+1] [j] +dfs [i] [j-1] +dfs [i] [j+1]
def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid: return 0 l,h = len(grid),len(grid[0]) def dfs(i,j): if 0 <= i < l and 0 <= j < h and grid[i][j]: grid[i][j] = 0 return 1 + dfs(i-1,j) + dfs(i+1,j) +dfs(i,j-1) + dfs(i,j+1) return 0 result = [dfs(i,j) for i in range(l) for j in range(h) if grid[i][j]] return max(result) if result else 0
在一個由 0 和 1 組成的二維矩陣內,找到只包含 1 的最大正方形,並返回其面積。
示例:
輸入: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 輸出: 4
public class Solution { public int maximalSquare(char[][] matrix) { if(matrix.length == 0) return 0; int m = matrix.length, n = matrix[0].length; int max = 0; int[][] dp = new int[m][n]; // 第一列賦值 for(int i = 0; i < m; i++){ dp[i][0] = matrix[i][0] - '0'; max = Math.max(max, dp[i][0]); } // 第一行賦值 for(int i = 0; i < n; i++){ dp[0][i] = matrix[0][i] - '0'; max = Math.max(max, dp[0][i]); } // 遞推 for(int i = 1; i < m; i++){ for(int j = 1; j < n; j++){ dp[i][j] = matrix[i][j] == '1' ? Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1])) + 1 : 0; max = Math.max(max, dp[i][j]); } } return max * max; } }