[LeetCode]Number of Islands,解題報告,leetcodeislands
目錄
前言
利用晚上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
思路
題目思路還是很簡單的,大體思路就是:
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);}