[LeetCode]Number of Islands,解題報告,leetcodeislands

來源:互聯網
上載者:User

[LeetCode]Number of Islands,解題報告,leetcodeislands
目錄

  • 目錄
  • 前言
  • 題目
  • 思路
  • 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

思路

題目思路還是很簡單的,大體思路就是:

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);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.