1. 程式人生 > >leetcode200. Number of Islands

leetcode200. Number of Islands

上下左右 new div 多個 public tin [] poi ber

題意:給一個0,1二維數組,求有多少塊“1”(多個1上下左右相連算一塊)

思路:DFS/BFS

DFS跑了6ms,BFS跑了12ms

DFS代碼:

class Solution {
    
    int lenx =0 , leny= 0 ;
    int[] cx = {1,-1,0,0}, cy = {0,0,1,-1};
    void dfs(char[][] grid, int tx, int ty){
        
        if(tx <0 || tx >= lenx || ty<0 || ty >= leny) return;
        if(grid[tx][ty] == ‘0‘) return
; grid[tx][ty] = ‘0‘; for(int i=0;i<4;i++) dfs(grid, tx+cx[i], ty+cy[i]); } public int numIslands(char[][] grid) { if(grid.length == 0) return 0; int ans = 0; lenx = grid.length; leny = grid[0].length;
for(int i=0;i<lenx;i++){ for(int j=0;j<leny;j++){ if(grid[i][j] == ‘0‘) continue; ans++; dfs(grid,i,j); } } return ans; } }

BFS代碼:

class Solution {
    
     
    
    public int
numIslands(char[][] grid) { if(grid.length == 0) return 0; int ans = 0; int lenx = grid.length, leny = grid[0].length; int[] cx = {1,-1,0,0}, cy = {0,0,1,-1}; for(int i=0;i<lenx;i++){ for(int j=0;j<leny;j++){ if(grid[i][j] == ‘0‘) continue; LinkedList<Point> qu = new LinkedList<>(); ans++; qu.add(new Point(i,j)); grid[i][j] = ‘0‘; while(qu.isEmpty() == false){ Point now = qu.remove(); int x = now.x, y = now.y; for(int k=0;k<4;k++){ int tx = x+cx[k], ty = y+cy[k]; if(tx <0 || tx >= lenx || ty<0 || ty >= leny) continue; if(grid[tx][ty] == ‘0‘) continue; grid[tx][ty] = ‘0‘; qu.add(new Point(tx,ty)); } } } } return ans; } }

leetcode200. Number of Islands