publicintnumIslands(char[][] grid) { n = grid.length; m = grid[0].length; intans=0; for (inti=0 ; i < n ; i++){ for (intj=0; j < m; j++){ if (grid[i][j] == '1'){ bfs(grid,i,j); ans++; } } } return ans; }
publicvoidbfs(char [][] g,int x,int y){ Queue<int[]> queue = newLinkedList<>(); queue.offer(newint[]{x,y}); while (!queue.isEmpty()){ vart= queue.poll(); for (inti=0 ; i < 4 ; i++){ inttx= t[0] + dx[i]; intty= t[1] + dy[i]; if (tx < 0 || tx >=n || ty < 0 || ty >= m){ continue; }