Given a 2d grid map ‘1‘
of S (land) ‘0‘
and S (water), count the number of islands. An island is surrounded by water and are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer:1
Example 2:
11000
11000
00100
00011
Answer:3
The main idea is to give a picture, looking for all the sub-graphs. Note two points: 1. The two-dimensional array is not necessarily a phalanx; 2. The array may be empty
The code is as follows:
1 Public classSolution {2 classPOS {3 Public intx;4 Public inty;5 6 PublicPosintXinty) {7 This. x =x;8 This. y =y;9 }Ten } One A Public intNumislands (Char[] grid) { - if(Grid.length = = 0) - return0; the intCount = 0; - intXL = grid.length, yl = grid[0].length; - int[] Visit =New int[Xl][yl]; -Linkedlist<pos> LP =NewLinkedlist<solution.pos>(); + POS cur; - for(inti = 0; I < XL; i++) { + for(intj = 0; J < yl; J + +) { A if(Grid[i][j] = = ' 0 ') at Continue; - if(Grid[i][j] = = ' 1 ' && visit[i][j] = = 1) - Continue; -Cur =NewPOS (i, j); - Lp.push (cur); - while(Lp.size () > 0) { inCur =Lp.poll (); -VISIT[CUR.X][CUR.Y] = 1; to if(cur.x + 1 < XL && grid[cur.x + 1][cur.y] = = ' 1 ' +&& visit[cur.x + 1][cur.y]! = 1) { -Lp.push (NewPOS (cur.x + 1, Cur.y)); the } * if(cur.x-1 >= 0 && grid[cur.x-1][cur.y] = = ' 1 ' $&& VISIT[CUR.X-1][CUR.Y]! = 1) {Panax NotoginsengLp.push (NewPOS (cur.x-1, Cur.y)); - } the if(Cur.y + 1 < yl && Grid[cur.x][cur.y + 1] = = ' 1 ' +&& VISIT[CUR.X][CUR.Y + 1]! = 1) { ALp.push (NewPOS (cur.x, CUR.Y + 1)); the } + if(cur.y-1 >= 0 && grid[cur.x][cur.y-1] = = ' 1 ' -&& visit[cur.x][cur.y-1]! = 1) { $Lp.push (NewPOS (cur.x, Cur.y-1)); $ } - } -++count; the } - }Wuyi the returncount; - } Wu - Public Static voidMain (string[] args) { About Char[] Grid1 = {{' 1 ', ' 1 ', ' 1 ', ' 1 ', ' 0 ' }, ${' 1 ', ' 1 ', ' 0 ', ' 1 ', ' 0 '}, {' 1 ', ' 1 ', ' 0 ', ' 0 ', ' 0 ' }, -{' 0 ', ' 0 ', ' 0 ', ' 0 ', ' 0 '}}, Grid2 = { -{' 1 ', ' 1 ', ' 0 ', ' 0 ', ' 0 '}, {' 1 ', ' 1 ', ' 0 ', ' 0 ', ' 0 ' }, -{' 0 ', ' 0 ', ' 1 ', ' 0 ', ' 0 '}, {' 0 ', ' 0 ', ' 0 ', ' 1 ', ' 1 '}}, Grid3 = { A{' 1 ', ' 1 ', ' 1 '}, {' 0 ', ' 1 ', ' 0 '}, {' 1 ', ' 1 ', ' 1 ' } }; +Solution s =Newsolution (); the System.out.println (S.numislands (GRID1)); - System.out.println (S.numislands (GRID2)); $ System.out.println (S.numislands (GRID3)); the } the}
I'm using breadth-first traversal, or I can try a depth-first traversal
Traversal-leetcode200 for Java graphs