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] = '#'; } } }}
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
- 9.3 Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- 热特瑞特让他热特让他
- 總論判讀 6-1
- PHP判断手机等移动设备示例代码
- php判断客户端是pc还是移动设备
- PHP生成一段时间之间的月份列表 实例代码
- 9.3 Surrounded Regions
- 而洗洁精膜会有效地保持玻璃2小时内不结霜
- 黑马程序员_枚举
- 类型转换
- 微信来了,云盘和云计算服务器也来了
- codeforces 258 A Game With Sticks(水题)
- csdn夏令营week2
- 在引入项目时,如何更改android工程名
- Codeforces Round #258 (Div. 2)