Why is the OJ result different from my ide?


  • 0
    S
     public class Solution {
            char[][] grid;
            int rows;
            int cols;
            int [][]mark;
            public void dfs(int i,int j){
                LinkedList<int[]> stack=new LinkedList<int[]>();
                stack.add(new int[]{i,j});
                while (!stack.isEmpty()){
                    int[] p=stack.removeLast();
                    int ii=p[0];
                    int jj=p[1];
                    mark[ii][jj]=1;
                    if(ii>0&&mark[ii-1][jj]==0&&grid[ii-1][jj]!=0){
                        stack.add(new int[]{ii-1,jj});
                    }
                    if(ii!=rows-1&&mark[ii+1][jj]==0&&grid[ii+1][jj]!=0){
                        stack.add(new int[]{ii+1,jj});
                    }
                    if(jj>0&&mark[ii][jj-1]==0&&grid[ii][jj-1]!=0){
                        stack.add(new int[]{ii,jj-1});
                    }
                    if(jj!=cols-1&&mark[ii][jj+1]==0&&grid[ii][jj+1]!=0){
                        stack.add(new int[]{ii,jj+1});
                    }
                }
            }
            public int numIslands(char[][] grid) {
                if(grid==null|grid.length==0||grid[0].length==0)
                    return 0;
                int n=0;
                this.grid=grid;
                 rows=grid.length;
                 cols=grid[0].length;
                mark=new int[rows][cols];
                for(int i=0;i<rows;++i){
                    for(int j=0;j<cols;++j){
                        if(grid[i][j]!=0&&mark[i][j]==0){
                            n++;
                            dfs(i,j);
                        }
                    }
                }
                return n;
            }
        }
    

    my test case

    @Test
        public void test()
        {
            Solution s=new Solution();
            char[][] map={
                    {1,1,0,0,0},
                    {1,1,0,0,1},
                    {0,0,1,1,1},
                    {1,0,0,1,1}
            };
            System.out.println(s.numIslands(map));
    
        }
    

Log in to reply
 

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