1、岛屿的最大面积
https://leetcode.cn/problems/ZL6zAn/
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int ans = 0;
for (int i = 0; i != grid.length; ++i) {
for (int j = 0; j != grid[0].length; ++j) {
ans = Math.max(ans, dfs(grid, i, j));
}
}
return ans;
}
public int dfs(int[][] grid, int cur_i, int cur_j) {
if (cur_i < 0 || cur_j < 0 || cur_i == grid.length || cur_j == grid[0].length || grid[cur_i][cur_j] != 1) {
return 0;
}
grid[cur_i][cur_j] = 0;
int[] di = {0, 0, 1, -1};
int[] dj = {1, -1, 0, 0};
int ans = 1;
for (int index = 0; index != 4; ++index) {
int next_i = cur_i + di[index], next_j = cur_j + dj[index];
ans += dfs(grid, next_i, next_j);
}
return ans;
}
}
2、##单词搜索
https://leetcode.cn/problems/word-search/
class Solution {
public boolean exist(char[][] board, String word) {
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(dfs(board,word,0,i,j)){
return true;
}
}
}
return false;
}
public boolean dfs(char[][] board,String word,int index,int x,int y){
if(x<0||x>board.length-1||y<0||y>board[0].length-1||board[x][y]=='.'||board[x][y]!=word.charAt(index)){
return false;
}
if(index==word.length()-1){
return true;
}else{
char temp=board[x][y];
board[x][y]='.';
boolean b=dfs(board,word,index+1,x+1,y)||dfs(board,word,index+1,x-1,y)||
dfs(board,word,index+1,x,y+1)||dfs(board,word,index+1,x,y-1);
board[x][y]=temp;
return b;
}
}
}