2020.3.29 力扣题目回顾
原题:点击此处
考点:最基础的DFS
题目:用来给新手做DFS练手题,见过无数次了。
题解:
1.用栈。
2.用递归。
这里用递归。
时间复杂度O(行数X列数)
空间复杂度O(行数X列数)
递归版代码:
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int line = grid.length;
int row = grid[0].length;
if(line == 0 || row == 0){
return 0;
}
int ans = 0;
for(int i =0;i<line;i++){
for(int j = 0;j<row;j++){
if(grid[i][j] == 1){
ans = Math.max(ans,dfs(grid,i,j));
}
}
}
return ans;
}
public int dfs(int[][] grid,int i,int j){
if(i < 0 || i >= grid.length || j < 0 || j>= grid[0].length || grid[i][j] == 0){
return 0;
}
int num = 1;
// 沉岛
grid[i][j] = 0;
int up = dfs(grid,i-1,j);
int down = dfs(grid,i+1,j);
int left = dfs(grid,i,j-1);
int right = dfs(grid,i,j+1);
num = num + up + down + left + right;
return num;
}
}
栈思想(自己写的很不简洁)
class Solution {
public int maxAreaOfIsland(int[][] grid) {
if(grid.length == 0 && grid[0].length == 0){
return 0;
}
Stack<Integer> st1 =new Stack<Integer>();
Stack<Integer> st2 = new Stack<Integer>();
int line= grid.length;
int row = grid[0].length;
boolean[][] visit = new boolean[line][row];
for(int i = 0; i< line; i++){
for(int j = 0 ; j< row; j++){
visit[i][j] = false;
}
}
int max = 0;
// 开始遍历
for(int i = 0 ; i< line ; i++){
for(int j = 0; j<row;j++){
// 有一的时候进入深度优先搜索
if(visit[i][j] == false && grid[i][j] == 1){
max = Math.max(dfs(st1,st2,grid,i,j,visit,line,row),max);
}
}
}
return max;
}
public int dfs(Stack<Integer> st1,Stack<Integer> st2,int[][] grid,int i,int j,boolean[][] vis,int line,int row){
// 当前肯定有一个点
int point = 1;
// 入栈
st1.push(i);
st2.push(j);
vis[i][j] = true;
int[] one = new int[]{1,-1};
// 只要栈不为空,就一直循环
while(!st1.empty()){
// 出栈
int left = st1.pop();
int right = st2.pop();
for(int m = 0; m < 2;m++){
//横向入栈
if((left+one[m])>=0 && (left+one[m]) < line && vis[left+one[m]][right] == false &&grid[left+one[m]][right]== 1){
st1.push(left+one[m]);
st2.push(right);
vis[left+one[m]][right] = true;
point++;
}
// 纵向入栈
if((right+one[m])>=0 && (right+one[m])<row && vis[left][right+one[m]] == false && grid[left][right+one[m]] == 1){
st1.push(left);
st2.push(right+one[m]);
vis[left][right+one[m]] = true;
point++;
}
}
}
return point;
}
}