1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: bool hasValidPath(vector<vector<char>> &grid) { int m = grid.size(), n = grid[0].size(); if (((m + n - 1) & 1) || grid[0][0] == ')' || grid[m - 1][n - 1] == '(') return false; 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) { if (c > m - x + n - y + 1) return false; if (x == m - 1 && y == n - 1) return c == 1; if (vis[x][y][c]) return false; 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)); }; return dfs(0, 0, 0); } };
|