今天的题目真滴难,一天都花在这上面,JAVA都没碰
1091.二进制矩阵中的最短路径
class Solution { public:
int shortestPathBinaryMatrix(vector<vector<int>> &grid) { int n = grid.size(); if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1; int length = 1; queue<int> q; grid[0][0] = 1; q.push(0); int dirX[8] = {0, 0, 1, -1, 1, 1, -1, -1}; int dirY[8] = {1, -1, 0, 0, 1, -1, 1, -1}; while (!q.empty()) { int qSize = q.size(); for (int i = 0; i < qSize; i++) { int x = q.front() % n; int y = q.front() / n; q.pop(); if (x == n - 1 && y == n - 1) return length; for (int i = 0; i < 8; i++) { if (x + dirX[i] < 0 || x + dirX[i] > n - 1 || y + dirY[i] < 0 || y + dirY[i] > n - 1 || grid[x + dirX[i]][y + dirY[i]]) continue; grid[x + dirX[i]][y + dirY[i]] = 1; q.push((y + dirY[i]) * n + x + dirX[i]); } } length++; } return -1; } };
|
130.被围绕的区域
class Solution { public: int dirX[4] = {1, 0, -1, 0}; int dirY[4] = {0, 1, 0, -1}; vector<vector<bool>> mark;
void solve(vector<vector<char>> &board) { mark = vector<vector<bool>>(board.size(), vector<bool>(board[0].size(), 0)); for (int i = 0; i < board.size(); i++) { if (board[i][board[0].size() - 1] == 'O') { search(board, board[0].size() - 1, i); } if (board[i][0] == 'O') { search(board, 0, i); } } for (int i = 0; i < board[0].size(); i++) { if (board[board.size() - 1][i] == 'O') { search(board, i, board.size() - 1); } if (board[0][i] == 'O') { search(board, i, 0); } } for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++) { if (board[i][j] == 'O' && !mark[i][j]) { board[i][j] = 'X'; } } } } void search(vector<vector<char>> &board, int x, int y) { if (x < 0 || x >= board[0].size() || y < 0 || y >= board.size() || board[y][x] != 'O' || mark[y][x]) return; mark[y][x] = 1; for (int i = 0; i < 4; i++) { search(board, x + dirX[i], y + dirY[i]); } } };
|
797.所有可能的路径
class Solution { public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph) { vector<int> arr{0}; vector<vector<int>> ans; func(graph, ans, arr, 0, graph.size() - 1); return ans; } void func(vector<vector<int>> &graph, vector<vector<int>> &ans, vector<int> &arr, int s, int e) { if (s == e) { ans.push_back(arr); return; } for (auto &i : graph[s]) { arr.push_back(i); func(graph, ans, arr, i, e); arr.pop_back(); } } };
|