9.3 Surrounded Regions

来源:互联网 发布:美工简历怎么写 编辑:程序博客网 时间:2024/06/07 16:01

Link: https://oj.leetcode.com/problems/surrounded-regions/


Appoach I: BFS

http://blog.csdn.net/linhuanmars/article/details/22904855

Time: O(m*n), Space: O(m+n) //Why?

public class Solution {    public void solve(char[][] board) {        // Start typing your Java solution below        // DO NOT write main() function        if(board==null || board.length <=1 || board[0].length <=1){            return;        }        //First record the 'O' on the four outer edges            //top row and bottom row         for(int j = 0; j < board[0].length; j++){            bfs(board, 0, j);            bfs(board, board.length-1, j);        }        //left col and right col         for(int i = 1; i < board.length - 1; i++){            bfs(board, i, 0);            bfs(board, i, board[0].length-1);        }        for(int i = 0; i < board.length; i++){            for(int j = 0; j < board[0].length; j++){                if(board[i][j] == 'O') board[i][j] = 'X';                else if (board[i][j] == '#') board[i][j] = 'O';            }        }    }        public void bfs(char[][]board, int x, int y){        Queue<Integer> queue = new LinkedList<Integer>();        if(board[x][y]!='O'){            return;        }        //if the outer edge board[x][y] == 'O', mark it as '#'        board[x][y] = '#';        int code = board[0].length*x + y;        queue.add(code);        //for those inner nodes connected to 'O' on the outer edges,         //because they are not surrounded with four 'X', also mark them as '#'        while(!queue.isEmpty()){            code = queue.poll();            x = code/board[0].length;             y = code%board[0].length;            if(y+1 <board[0].length && board[x][y+1] =='O'){//top:[x][y]=='O'&&[x][y+1]=='O'                queue.add(board[0].length*x + y + 1);                board[x][y+1] = '#';            }            if(y-1 >=0 && board[x][y-1] =='O'){//bottom                queue.add(board[0].length*x + y - 1);                board[x][y-1] = '#';            }            if(x-1>=0 && board[x-1][y] =='O'){//left                queue.add(board[0].length*(x-1) + y);                board[x-1][y] = '#';            }            if(x+1<board.length && board[x+1][y] =='O'){//right                queue.add(board[0].length*(x+1) + y);                board[x+1][y] = '#';            }            }    }}


Approach II: DFS

See my leetcode submissions

 (Online solutions have Time Limit Exceeded or Stack Overflow problem). 

But I need to know how to code. //todo

0 0
原创粉丝点击