Home > database >  time limit exceeded for algorithm question in Java "Number of Islands"
time limit exceeded for algorithm question in Java "Number of Islands"

Time:12-15

for leetcode 200 Number of Islands, this solution works fine. However, for the lower solution, the submission fails due to time limit exceeded. In my understanding, both solution should run in the same time. Would you please help on this?

class Solution {
    // BFS time O(mn) | space O(min(m,n))
    public int numIslands(char[][] grid) {
        int islandsCount = 0;
        for (int i = 0; i < grid.length; i  ) {
            for (int j = 0; j < grid[0].length; j  ) {
                if (grid[i][j] == '1') {
                    islandsCount  ;
                    bfs(grid, i, j);
                }
            }
        }
        return islandsCount;
    }

    public static void bfs(char[][] grid, int row, int col) {
        int rc = grid.length;
        int cc = grid[0].length;
        Deque<Integer> queue = new ArrayDeque<Integer>();
        queue.offer(row*cc   col);
        while (!queue.isEmpty()) {
            Integer spotIdx = queue.poll();
            int i = spotIdx/cc, j = spotIdx           
  • Related