Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5caf2dc

Browse files
author
applewjg
committed
SurroundedRegions
Change-Id: I5e4b11be68f210ac7380d8853abe968e24b997ab
1 parentef3c0f2 commit5caf2dc

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎SurroundedRegions.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 20, 2015
4+
Problem: Surrounded Regions
5+
Difficulty: Easy
6+
Source: http://leetcode.com/onlinejudge#question_130
7+
Notes:
8+
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
9+
A region is captured by flipping all 'O's into 'X's in that surrounded region .
10+
For example,
11+
X X X X
12+
X O O X
13+
X X O X
14+
X O X X
15+
After running your function, the board should be:
16+
X X X X
17+
X X X X
18+
X X X X
19+
X O X X
20+
21+
Solution: Traverse from the boarder to the inside and mark all the 'O's that are not surrounded by 'X' as 'V' (visited).
22+
1. BFS (queue).
23+
*/
24+
publicclassSolution {
25+
publicvoidsolve(char[][]board) {
26+
if (board.length ==0 ||board[0].length ==0)return;
27+
intM =board.length,N =board[0].length;
28+
for (inti =0;i <M; ++i) {
29+
for (intj =0;j <N; ++j) {
30+
if (i ==0 ||j ==0 ||i ==M -1 ||j ==N -1) {
31+
bfs(board,i,j);
32+
}
33+
}
34+
}
35+
for (inti =0;i <M; ++i)
36+
for (intj =0;j <N; ++j)
37+
board[i][j] = (board[i][j] =='V') ?'O' :'X';
38+
}
39+
publicvoidbfs(char[][]board,introw,intcol) {
40+
if (board[row][col] !='O')return;
41+
intM =board.length,N =board[0].length;
42+
Queue<Integer>q =newLinkedList<Integer>();
43+
q.offer(row);q.offer(col);
44+
while (q.isEmpty() ==false) {
45+
inti =q.poll();intj =q.poll();
46+
if (i <0 ||i ==M ||j <0 ||j ==N)continue;
47+
if (board[i][j] !='O')continue;// important to recheck!
48+
board[i][j] ='V';
49+
q.offer(i-1);q.offer(j);
50+
q.offer(i+1);q.offer(j);
51+
q.offer(i);q.offer(j-1);
52+
q.offer(i);q.offer(j+1);
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp