题目
1-思路
2- 实现
⭐200. 岛屿数量——题解思路
class Solution {
public int numIslands ( char [ ] [ ] grid) {
int res = 0 ;
for ( int i = 0 ; i < grid. length; i++ ) {
for ( int j = 0 ; j < grid[ 0 ] . length; j++ ) {
if ( grid[ i] [ j] == '1' ) {
res++ ;
dfs ( grid, i, j) ;
}
}
}
return res;
}
public void dfs ( char [ ] [ ] grid, int i , int j) {
if ( i< 0 || i >= grid. length || j< 0 || j>= grid[ 0 ] . length || 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 ) ;
}
}
3- ACM实现
public class islandDFS {
public static int numIslands ( char [ ] [ ] grid) {
int res = 0 ;
for ( int i = 0 ; i < grid. length; i++ ) {
for ( int j = 0 ; j < grid[ 0 ] . length; j++ ) {
if ( grid[ i] [ j] == '1' ) {
res++ ;
dfs ( grid, i, j) ;
}
}
}
return res;
}
public static void dfs ( char [ ] [ ] grid, int i , int j) {
if ( i< 0 || i >= grid. length || j< 0 || j>= grid[ 0 ] . length || 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 ) ;
}
public static void main ( String [ ] args) {
Scanner scanner = new Scanner ( System . in) ;
int m = scanner. nextInt ( ) ;
int n = scanner. nextInt ( ) ;
scanner. nextLine ( ) ;
char [ ] [ ] grid = new char [ m] [ n] ;
for ( int i = 0 ; i < m; i++ ) {
String line = scanner. nextLine ( ) ;
String [ ] numbers = line. split ( " " ) ;
for ( int j = 0 ; j < n; j++ ) {
grid[ i] [ j] = numbers[ j] . charAt ( 0 ) ;
}
}
int count = numIslands ( grid) ;
System . out. println ( count) ;
}
} s