Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
public int islandsNum(char[][] grid){
int row=grid.length;
int col=grid[0].length;
int num=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]!='0'){
dfs(grid,i,j);
num++;
}
}
}
return num;
}
private void dfs(char[][] grid, int i, int j) {
int row=grid.length;
int col=grid[0].length;
if(i<0 || j<0 ||i>=row || j>=col || grid[i][j]== '0'){
return;
}
grid[i][j]='0';
dfs(grid,i-1,j);
dfs(grid,i+1,j);
dfs(grid,i,j-1);
dfs(grid,i,j+1); }
2.Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
public boolean isExists(char[][] grid,String str){
if(grid.length==0 || str.length()==0){
return false;
}
else{
int row=grid.length;
int col=grid[0].length;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if( dfs(grid,str,i,j,0))
return true;
}
}
}
return false;
}
/**
* @param grid
* @param str
* @param i
* @param j
* @param k
* @return
*<p>Description: </p>
*/
private boolean dfs(char[][] grid, String str, int i, int j, int strIndex) {
int row=grid.length;
int col=grid[0].length;
if(i >= row || j >= col || i<0 || j<0){
return false;
}
if(strIndex>=str.length()){
return true;
}
if(grid[i][j]!=str.charAt(strIndex)){
return false;
}
grid[i][j]='#';
if(dfs(grid,str,i-1,j,strIndex+1)){
return true;
}
if(dfs(grid,str,i+1,j,strIndex+1)){
return true;
}
if(dfs(grid,str,i,j-1,strIndex+1)){
return true;
}
if(dfs(grid,str,i,j+1,strIndex+1)){
return true;
}
grid[i][j]=str.charAt(strIndex);
return false;
}
网友评论