130.被围绕的区域
DFS,比较好写
int m=0;
int n=0;
public void solve(char[][] board) {
m=board.length;
n=board[0].length;
for(int i=0;i<m;i++){
dfs(board,i,0);
dfs(board,i,n-1);
}
for(int i=0;i<n;i++){
dfs(board,0,i);
dfs(board,m-1,i);
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='O'){
board[i][j]='X';
}
if(board[i][j]=='#'){
board[i][j]='O';
}
}
}
}
public void dfs(char[][] board,int x,int y){
if(x<0||x>=m||y<0||y>=n){
return;
}
if(board[x][y]!='O'){
return;
}else{
board[x][y]='#';
dfs(board,x-1,y);
dfs(board,x+1,y);
dfs(board,x,y-1);
dfs(board,x,y+1);
}
}
797. 所有可能的路径
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
DFS(0, graph, new LinkedList<>());
return ans;
}
private void DFS(int cur, int[][] graph, LinkedList<Integer> list) {
if (cur == graph.length - 1) {
list.add(cur);
ans.add(new ArrayList<>(list));
return;
}
list.add(cur);
for(int i=0;i<graph[cur].length;i++){
DFS(graph[cur][i],graph,list);
list.removeLast();
}
}
62. 不同路径
使用动态规划
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for(int i = 0; i < m; ++i) {
dp[i][0] = 1;
}
for(int j = 0; j < n; ++j) {
dp[0][j] = 1;
}
for(int i = 1; i < m; ++i) {
for(int j = 1; j < n; ++j) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
}
题解
63.不同路径 II
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length;
int m = obstacleGrid[0].length;
int[][] dp = new int[n][m];
dp[0][0] = (obstacleGrid[0][0] == 1) ? 0 : 1;
for(int i = 1; i < n; ++i) {
if(obstacleGrid[i][0] == 1 || dp[i - 1][0] == 0) {
dp[i][0] = 0;
} else {
dp[i][0] = 1;
}
}
for(int j = 1; j < m; ++j) {
if(obstacleGrid[0][j] == 1 || dp[0][j - 1] == 0) {
dp[0][j] = 0;
} else {
dp[0][j] = 1;
}
}
for(int i = 1; i < n; ++i) {
for(int j = 1; j < m; ++j) {
if(obstacleGrid[i][j] == 1) {
dp[i][j] = 0;
} else {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[n - 1][m - 1];
}
64.最小路径和
动态规划
public int minPathSum(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = grid[0][0];
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
for (int i = 1; i < n; i++) {
dp[0][i] = dp[0][i - 1] + grid[0][i];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[m - 1][n - 1];
}
|