您的位置:首页 > 其它

[LeetCode]Number of Islands,解题报告

2015-04-15 23:43 351 查看

目录

目录

前言

题目

思路

AC代码

我的疑问

前言

利用晚上11点之后的时间刷刷LeetCode也是我的一种休闲方式。不过水这篇博客是因为这道简单的BFS题目我竟然用了13次才AC,最后AC还是因为我参考了别人的答案,稍后我会说一下我对这道题的疑惑。

先贴出这道题目我艰难的AC过程:



中间那次313ms的ac答案是我直接把别人的AC代码贴上,因为当时我怀疑这道题目答案是否出了问题。

题目

Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110

11010

11000

00000

Answer: 1

Example 2:

11000

11000

00100

00011

Answer: 3

思路

题目思路还是很简单的,大体思路就是:

声明一个二维的visited数组,初始化为false,表示所有的点均没有访问过。

2层for循环遍历grid数组,遇到没有被访问过的‘1’之后,开始利用BFS思路遍历1周围的1,并将其标记为已访问。

进行了几次BFS,就说明有几个孤岛。

AC代码

public class Solution {
public int numIslands(char[][] grid) {
int res = 0;

if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}

int row = grid.length;
int col = grid[0].length;

// 初始化visited数组
boolean[][] visited = new boolean[row][col];
int[][] directions = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
Deque<Integer> queue = new ArrayDeque<Integer>();

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '0' || visited[i][j]) {
continue;
}

int loc = i * col + j;
queue.add(loc);
res += 1;
while (!queue.isEmpty()) {
loc = queue.poll();
int tpx = loc / col;
int tpy = loc % col;
if (visited[tpx][tpy]) {
continue;
}

visited[tpx][tpy] = true;

for (int k = 0; k < 4; k++) {
int x = tpx + directions[k][0];
int y = tpy + directions[k][1];

if (x >= 0 && x < row && y >= 0 && y < col && grid[x][y] == '1') {
queue.add(x * col + y);
}
}
}
}
}

return res;
}
}


我的疑问

BFS+剪枝是做这种题目的固定思路,但是我遇到了一个很蛋疼的问题,希望有思路的读者帮我解答一下。

问题就是,如果我将剪纸代码放入for循环中,LeetCode就会判定超时:

if (x >= 0 && x < row && y >= 0 && y < col && grid[x][y] == '1' && visited[x][y] == false) {
queue.add(x * col + y);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode