can I use try catch to catch the out of boundary ? it is fine? or it is not beauty?


  • 0
    J

    class Coor{
    int x;
    int y;
    Coor(int x, int y){
    this.x = x;
    this.y = y;
    }
    }
    public class Solution {
    public int numIslands(char[][] grid) {
    int[] directionX = {1, -1, 0, 0};
    int[] directionY = {0, 0, -1, 1};
    if(grid == null || grid.length == 0 || grid[0].length == 0 ) return 0;

        int row = grid.length;
        int col = grid[0].length;
        int result = 0;
        Queue<Coor> queue = new LinkedList<>();
        
        for(int i = 0; i <  row; i++){
            for(int j = 0; j < col; j++){
                if(grid[i][j] == '1'){ 
                    queue.offer(new Coor(i , j));
                    grid[i][j] = '0';
                    //do the bfs
                    while(!queue.isEmpty()){
                        Coor temp = queue.poll();
                        for(int k = 0; k < 4; k++){
                          try{  
                               Coor tempIsTemp = new Coor(temp.x + directionX[k], temp.y + directionY[k]);
                            // if(grid[tempIsTemp.x][tempIsTemp.y] == null){
                            //     continue;
                            // }
                            
                                if(grid[tempIsTemp.x][tempIsTemp.y] == '1'){
                                   queue.offer(tempIsTemp);
                                   grid[tempIsTemp.x][tempIsTemp.y] ='0';
                                }
                                
                            }catch(Exception exp){//it might be on the outside of this grid, 
                                continue;
                            }
                        }
                    }//end w
                    
                    result += 1;
                }
                
            }
        }//
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.