1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { bool flag = 0; int n, m; bool vis[105][105][205] = { 0 }; int st[2][2] = { {0,1},{1,0} }; inline void dfs(int cnt, int x, int y, vector<vector<char>>& grid) {
if (grid[x][y] == '(') cnt++; else cnt--; if(cnt<0) return; if (flag) return; if (x == n - 1 && y == m - 1) { flag |= cnt == 0; return; }
if (vis[x][y][cnt]) return; vis[x][y][cnt] = 1; int xx, yy; for (int i = 0; i < 2 ; i++) { xx = x + st[i][0], yy = y + st[i][1]; if (xx < n && yy < m) dfs(cnt, xx, yy, grid); } } public: bool hasValidPath(vector<vector<char>>& grid) { n = grid.size(); if (!n) return 0; m = grid[0].size(); if ((m + n+1) % 2 || grid[n - 1][m - 1] == '(' || grid[0][0] == ')') return 0; dfs(0, 0, 0, grid); return flag; } };
|