share my dfs solution!


  • 0
    C
    public class Solution {
        private int leftbound=0;
        private int rightbound=0;
        private int upbound=0;
        private int lowbound=0;
        
        public int minArea(char[][] image, int x, int y) {
            if(image==null||image.length<1) return 0;
            
            upbound=lowbound=x;
            leftbound=rightbound=y;
            dfs(image,x,y,new boolean[image.length][image[0].length]);
            return (rightbound-leftbound+1)*(lowbound-upbound+1);
        }
        
        public void dfs(char[][] image,int x,int y, boolean[][] visited){
            if(x<0||x>=image.length||y<0||y>=image[0].length||visited[x][y]||image[x][y]=='0') return;
            
            visited[x][y]=true;
            
            leftbound=Math.min(leftbound,y);
            rightbound=Math.max(rightbound,y);
            
            upbound=Math.min(upbound,x);
            lowbound=Math.max(lowbound,x);
            
            int[][] dirs=new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
            
            for(int[] dir:dirs){
                int m=dir[0];
                int n=dir[1];
                dfs(image,m+x,n+y,visited);
            }
        }
    }
    
    
    

Log in to reply
 

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