@cache # 效果类似 vis 数组 defdfs(x: int, y: int, c: int) -> bool: if c > m - x + n - y - 1: returnFalse# 剪枝:即使后面都是 ')' 也不能将 c 减为 0 if x == m - 1and y == n - 1: return c == 1# 终点一定是 ')' c += 1if grid[x][y] == '('else -1 return c >= 0and (x < m - 1and dfs(x + 1, y, c) or y < n - 1and dfs(x, y + 1, c)) # 往下或者往右 return dfs(0, 0, 0) # 起点
classSolution { int m, n; char[][] grid; boolean[][][] vis;
publicbooleanhasValidPath(char[][] grid) { m = grid.length; n = grid[0].length; if ((m + n) % 2 == 0 || grid[0][0] == ')' || grid[m - 1][n - 1] == '(') returnfalse; // 剪枝 this.grid = grid; vis = newboolean[m][n][(m + n + 1) / 2]; return dfs(0, 0, 0); }
booleandfs(int x, int y, int c) { if (c > m - x + n - y - 1) returnfalse; // 剪枝:即使后面都是 ')' 也不能将 c 减为 0 if (x == m - 1 && y == n - 1) return c == 1; // 终点一定是 ')' if (vis[x][y][c]) returnfalse; // 重复访问 vis[x][y][c] = true; c += grid[x][y] == '(' ? 1 : -1; return c >= 0 && (x < m - 1 && dfs(x + 1, y, c) || y < n - 1 && dfs(x, y + 1, c)); // 往下或者往右 } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: boolhasValidPath(vector<vector<char>> &grid){ int m = grid.size(), n = grid[0].size(); if ((m + n) % 2 == 0 || grid[0][0] == ')' || grid[m - 1][n - 1] == '(') returnfalse; // 剪枝 bool vis[m][n][(m + n + 1) / 2]; memset(vis, 0, sizeof(vis)); function<bool(int, int, int)> dfs = [&](int x, int y, int c) -> bool { if (c > m - x + n - y - 1) returnfalse; // 剪枝:即使后面都是 ')' 也不能将 c 减为 0 if (x == m - 1 && y == n - 1) return c == 1; // 终点一定是 ')' if (vis[x][y][c]) returnfalse; // 重复访问 vis[x][y][c] = true; c += grid[x][y] == '(' ? 1 : -1; return c >= 0 && (x < m - 1 && dfs(x + 1, y, c) || y < n - 1 && dfs(x, y + 1, c)); // 往下或者往右 }; returndfs(0, 0, 0); } };
funchasValidPath(grid [][]byte)bool { m, n := len(grid), len(grid[0]) if (m+n)%2 == 0 || grid[0][0] == ')' || grid[m-1][n-1] == '(' { // 剪枝 returnfalse }
vis := make([][][]bool, m) for i := range vis { vis[i] = make([][]bool, n) for j := range vis[i] { vis[i][j] = make([]bool, (m+n+1)/2) } } var dfs func(x, y, c int)bool dfs = func(x, y, c int)bool { if c > m-x+n-y-1 { // 剪枝:即使后面都是 ')' 也不能将 c 减为 0 returnfalse } if x == m-1 && y == n-1 { // 终点 return c == 1// 终点一定是 ')' } if vis[x][y][c] { // 重复访问 returnfalse } vis[x][y][c] = true if grid[x][y] == '(' { c++ } elseif c--; c < 0 { // 非法括号字符串 returnfalse } return x < m-1 && dfs(x+1, y, c) || y < n-1 && dfs(x, y+1, c) // 往下或者往右 } return dfs(0, 0, 0) // 起点 }