question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
word-ladder-ii | 25 ms | Use less memory than 97% | BFS + DFS | Golang | | 25-ms-use-less-memory-than-97-bfs-dfs-go-o53f | Let consider each string in wordList as a vertex on a graph, and if two strings differ by at most one character, we will connect an edge with weight 1 between t | mbfibat | NORMAL | 2022-08-14T08:40:53.377936+00:00 | 2022-08-14T08:42:05.353066+00:00 | 474 | false | - Let consider each string in ```wordList``` as a vertex on a graph, and if two strings differ by at most one character, we will connect an edge with weight ```1``` between them. The problem become: "Find the shortest path, single source, single destination, on a graph where each edge\'s weight is equal to 1".\n\n- The aforementioned problem is a basic BFS implementation, where the source vertex is ```beginWord```, and the destination is ```endWord```. Since I\'m a new user in Golang, I\'m not sure if storing each state in a hashmap the correct way to do this(?) Please let me know in the comment for a better way.\n\n- After having calculated the distance between each vertex to the source, we can simply use a recursive function to find all the solutions. \n\n- **Note:** I\'m not sure if the number of solutions are too large are not. If it\'s too big, there\'s no way we can find all the solutions using recursive function, as it would take forever.\n\n***Implementation:***\n```\nfunc difChar(a, b string) int { // Function to calculate the number of different chars between 2 strings\n ans := 0\n for id, _ := range a {\n if a[id] != b[id] {\n ans++\n }\n } \n return ans\n}\n\nfunc findLadders(beginWord string, endWord string, wordList []string) [][]string {\n mp := map[string]int{beginWord:0} // Hashmap to store the distance to the source, also set mp[beginWord] = 0\n q := make([]string, 0) // Queue to BFS\n q = append(q, beginWord) // Insert the source to the queue\n for len(q) > 0 { // While the queue is not empty\n curWord := q[0] // Get the front of the queue\n q = q[1:] // Remove the front of the queue\n for _, nxtWord := range wordList { // Iterate all next states\n if _, have := mp[nxtWord]; !have && difChar(curWord, nxtWord) == 1 { // If the next state has not been visited yet\n q = append(q, nxtWord) // We push it to the queue\n mp[nxtWord] = mp[curWord] + 1 // And update the distance\n }\n }\n }\n \n ans := [][]string{} // Initialize the answer\n if _, have := mp[endWord]; !have { // If we can\'t reach the end vertex\n return ans // Return empty\n }\n\n var dfs func(curWord string, cur []string) \n dfs = func(curWord string, cur []string) { // Anonymous function for inserting into answer easier\n cur = append(cur, curWord) // Insert the current string \n if (mp[curWord] == 1) { // If we has reach the end state\n cur = append(cur, beginWord) // Insert beginWord, since we stop at distance = 1\n tmp := cur // Remember to reverse the current string list\n for i, j := 0, len(tmp)-1; i < j; i, j = i + 1, j - 1 {\n tmp[i], tmp[j] = tmp[j], tmp[i]\n }\n ans = append(ans, tmp) // Add it to answer\n cur = cur[:len(cur)-2] // And remove the new two just-added strings\n return;\n } \n for _, nxtWord := range wordList {\n if _, have := mp[nxtWord]; have && difChar(curWord, nxtWord) == 1 && mp[curWord] == mp[nxtWord] + 1 {\n dfs(nxtWord, cur)\n }\n } \n cur = cur[:len(cur)-1] // Remove the last string\n }\n dfs(endWord, []string{}) // Begin recursion\n \n return ans\n}\n``` | 5 | 0 | ['Depth-First Search', 'Binary Search Tree', 'Go'] | 0 |
word-ladder-ii | C++ | Floyd-Warshall + BFS | O(n^3) | explanation | c-floyd-warshall-bfs-on3-explanation-by-kbcyg | \nclass Solution {\npublic:\n vector <int> isc[501];\n long dis[501][501];\n int n,tar,as;\n bool jc(string x,string y){\n int v=0;\n | SunGod1223 | NORMAL | 2022-08-14T05:05:52.716261+00:00 | 2022-08-14T11:48:54.330411+00:00 | 421 | false | ```\nclass Solution {\npublic:\n vector <int> isc[501];\n long dis[501][501];\n int n,tar,as;\n bool jc(string x,string y){\n int v=0;\n for(int i=0;i<x.size();++i)\n if(x[i]!=y[i])++v;\n return v==1;\n }\n vector<vector<string>> findLadders(string bW, string eW, vector<string>& wL) {\n vector<vector<string>> rt;\n n=wL.size();\n memset(dis,0x3f,sizeof(dis));\n for(int i=0;i<n;++i){\n if(wL[i]==eW)tar=i+1;\n if(jc(wL[i],bW)){\n isc[0].push_back(i+1);\n dis[0][i+1]=dis[i+1][0]=1;\n }\n for(int j=i+1;j<n;++j)\n if(jc(wL[i],wL[j])){\n isc[i+1].push_back(j+1);\n isc[j+1].push_back(i+1);\n dis[j+1][i+1]=dis[i+1][j+1]=1;\n }\n }\n if(tar==0)return rt;\n for(int k=0;k<=n;++k)\n for(int i=0;i<=n;++i)\n for(int j=0;j<=n;++j)\n if(dis[i][j]>dis[i][k]+dis[k][j])\n dis[i][j]=dis[i][k]+dis[k][j];\n as=dis[0][tar];\n queue <vector <int>> q;\n vector <int> v;\n v.push_back(0);\n q.push(v);\n dis[tar][tar]=0;\n while(!q.empty()){\n v=q.front();q.pop();\n int tp=v.back();\n if(tp==tar){\n vector <string> vs;\n vs.push_back(bW);\n for(int i=1;i<=as;++i)\n vs.push_back(wL[v[i]-1]);\n rt.push_back(vs);\n continue;\n }\n for(int i=0;i<isc[tp].size();++i){\n if(dis[isc[tp][i]][tar]==dis[tp][tar]-1){\n vector <int> tv=v;\n tv.push_back(isc[tp][i]);\n q.push(tv);\n }\n }\n }\n return rt;\n }\n};\n```\n1.First find all connected words.In the concept of graph, their distance is 1.\n2.Find the shortest distance of all pairs by using Floyd-Warshall.\n3.If dis(\'start\',\'end\') = 20,than the next target for \'start\' is obviously all points x with dis(x,\'end\') = 19.\n4.Remember to check if the two strings are connected.\n | 5 | 0 | ['Breadth-First Search'] | 0 |
word-ladder-ii | Java Solution using BFS and memorized DFS | java-solution-using-bfs-and-memorized-df-075w | Step1: use BFS to build a Ladder Graph start from beginWord layer and end to endWord layer\nStep2: use memorized DFS to traverse the graph and found all the sho | 1005155946 | NORMAL | 2022-07-07T10:14:54.298885+00:00 | 2022-07-07T10:14:54.298925+00:00 | 1,079 | false | Step1: use BFS to build a Ladder Graph start from beginWord layer and end to endWord layer\nStep2: use memorized DFS to traverse the graph and found all the shortest route\n``` java\nclass Solution {\n Map<String, List<List<String>>> buf;\n public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n if (!remove(wordList, endWord)) return new ArrayList<>();\n remove(wordList, beginWord);\n wordList.add(endWord);\n buf = new HashMap<>();\n Map<String, List<String>> graph = buildLadderGraph(beginWord, endWord, wordList);\n traverseLadderGraph(graph, beginWord, endWord);\n return buf.getOrDefault(beginWord, new ArrayList<>());\n }\n\n private List<List<String>> traverseLadderGraph(Map<String, List<String>> graph, String beginWord, String endWord) {\n if (beginWord.equals(endWord)) {\n buf.put(beginWord, new ArrayList<>());\n buf.get(beginWord).add(new ArrayList<>(Arrays.asList(endWord)));\n return buf.get(beginWord);\n }\n if (buf.containsKey(beginWord)) return buf.get(beginWord);\n if (!graph.containsKey(beginWord)) return new ArrayList<>();\n List<List<String>> next = new ArrayList<>();\n for (String s : graph.get(beginWord)) {\n next.addAll(traverseLadderGraph(graph, s, endWord));\n }\n buf.put(beginWord, new ArrayList<>());\n for (List<String> route : next) {\n List<String> l = new ArrayList<>(route);\n l.add(0, beginWord);\n buf.get(beginWord).add(l);\n }\n return buf.get(beginWord);\n }\n\n private Map<String, List<String>> buildLadderGraph(String beginWord, String endWord, List<String> wordList) {\n Map<String, List<String>> map = new HashMap<>();\n Set<String> needDelete = new HashSet<>();\n Queue<String> q = new LinkedList<>();\n q.offer(beginWord);\n boolean flag = false;\n int size = q.size();\n while (!q.isEmpty()) {\n String s = q.poll();\n map.put(s, new ArrayList<>());\n for (String word : wordList) {\n if (isLadder(word, s)) {\n if (!needDelete.contains(word)) q.offer(word);\n needDelete.add(word);\n map.get(s).add(word);\n if (word.equals(endWord)) flag = true;\n }\n }\n if (--size == 0) {\n if (flag) break;\n int len = wordList.size();\n for (int i = 0; i < len; i++) if (!needDelete.contains(wordList.get(i))) wordList.add(wordList.get(i));\n wordList = wordList.subList(len, wordList.size());\n needDelete = new HashSet<>();\n size = q.size();\n }\n }\n return map;\n }\n\n private boolean remove(List<String> wordList, String endWord) {\n for (int i = 0; i < wordList.size(); i++) {\n if (wordList.get(i).equals(endWord)) {\n Collections.swap(wordList, i, wordList.size() - 1);\n wordList.remove(wordList.size() - 1);\n return true;\n }\n }\n return false;\n }\n\n private boolean isLadder(String a, String b) {\n int diff = 0;\n for (int i = 0; i < a.length(); i++) if (a.charAt(i) != b.charAt(i)) diff++;\n return diff == 1;\n }\n}\n``` | 5 | 1 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'Java'] | 1 |
word-ladder-ii | Python - BFS - very simple | python-bfs-very-simple-by-edgoll-3tpo | \n\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \n wordList.append(beginWord)\n nei | edgoll | NORMAL | 2022-01-26T05:20:10.511728+00:00 | 2022-01-26T05:20:10.511760+00:00 | 420 | false | \n\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \n wordList.append(beginWord)\n nei = collections.defaultdict(list)\n \n #Creating adjs list using pattern over the words\n for w in wordList :\n for k in range(len(w)) :\n pattern = w[:k] + \'-\' + w[k + 1:]\n nei[pattern].append(w)\n \n q = collections.deque([(beginWord, [beginWord])])\n vis = set([beginWord])\n res = []\n \n while q :\n auxSet = set() #this enable have control over the graph paths. The key for this problem\n \n for s in range(len(q)) :\n w, seq = q.popleft()\n if w == endWord :\n res.append(seq) \n \n for k in range(len(w)) : #sech adjs list \n pattern = w[:k] + \'-\' + w[k + 1:]\n for adj in nei[pattern] :\n if adj not in vis : \n auxSet.add(adj)\n q.append((adj, seq[:]+[adj]))\n \n vis.update(auxSet) \n\n return res | 5 | 0 | ['Python'] | 1 |
word-ladder-ii | Simple Python BFS solution with 20 lines of code and explanation, beats 80%! | simple-python-bfs-solution-with-20-lines-mrzz | Steps:\n1. Construct an adjecncy list from the wordList\n2. Perform normal BFS with a queue (every element is a tuple of currentWord, the list of words from beg | darshangowda0 | NORMAL | 2020-08-02T06:16:31.179273+00:00 | 2020-08-02T06:16:31.179306+00:00 | 470 | false | Steps:\n1. Construct an adjecncy list from the wordList\n2. Perform normal BFS with a queue (every element is a tuple of currentWord, the list of words from beginWord to currentWord)\n3. Everytime you find the endWord, add the list built so far to the output list!\n\n**Main STEP to help aviod TLE:**\nDo not visit the same node/word again if it was visited at an earlier timestamp, because it would lead the result to same list that will be created from the earlier visited word. (Maintain a dictionary of visited word and timestamp at which they were visited)\n\nCode:\n\n```\nclass Solution:\n \n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \n # construct an adjacency list with the dictionary\n adjList = defaultdict(list)\n \n for word in wordList:\n for i in range(len(word)):\n _key = word[:i] + "*" + word[i+1:]\n adjList[_key] += word,\n \n # perform bfs\n \n que = deque([(beginWord,[beginWord])]) # que has (word, [visitedListTillNow])\n res = []\n visited = {beginWord:1} #maintain a visited dictionary with visit time\n \n while len(que) > 0:\n word, _list = que.popleft()\n dist = len(_list) #distance from beginWord\n \n if word == endWord: #if found, add to result\n res += _list,\n continue\n \n for i in range(len(word)):\n _key = word[:i] + "*" + word[i+1:]\n for child in adjList[_key]:\n # if the node is already visited in a previos timestamp, ignore it\n if child not in visited or dist <= visited[child]:\n que += (child,_list[:]+[child]),\n visited[child] = dist\n \n return res\n``` | 5 | 0 | [] | 3 |
word-ladder-ii | C# BFS | c-bfs-by-user638-rcn7 | \npublic class Solution\n{\n public IList<IList<string>> FindLadders(string beginWord, string endWord, IList<string> wordList)\n {\n var map = new | user638 | NORMAL | 2020-04-16T16:18:11.820378+00:00 | 2020-04-16T16:19:13.934861+00:00 | 556 | false | ```\npublic class Solution\n{\n public IList<IList<string>> FindLadders(string beginWord, string endWord, IList<string> wordList)\n {\n var map = new Dictionary<string, List<string>>();\n wordList.Add(beginWord);\n wordList = wordList.Distinct().ToList();\n for (var i = 0; i < wordList.Count; i++)\n for (var j = 0; j < wordList.Count; j++)\n if (i != j && Diff(wordList[i], wordList[j]) == 1)\n if (!map.ContainsKey(wordList[i])) map[wordList[i]] = new List<string>() { wordList[j] };\n else map[wordList[i]].Add(wordList[j]);\n\n var res = new List<IList<string>>();\n var hs = new HashSet<string>() { beginWord };\n\n\n var nodes = new List<(string, List<string> Path)>() { (beginWord, new List<string>()) };\n\n while (nodes.Any())\n {\n var newNodes = new List<(string, List<string> Path)>();\n foreach (var (node, path) in nodes)\n if (node == endWord)\n {\n path.Add(node);\n res.Add(path);\n }\n else if (map.ContainsKey(node))\n foreach (var next in map[node])\n if (!hs.Contains(next))\n {\n var newPath = new List<string>(path);\n newPath.Add(node);\n newNodes.Add((next, newPath));\n }\n\n foreach (var (node, path) in newNodes)\n hs.Add(node);\n nodes = newNodes.ToList();\n }\n\n return res;\n }\n\n private int Diff(string s, string s2)\n {\n var d = 0;\n for (var i = 0; i < s.Length; i++)\n if (s[i] != s2[i]) d++;\n return d;\n }\n}\n``` | 5 | 0 | ['Breadth-First Search'] | 1 |
word-ladder-ii | Intuitive Javascript Solution with BFS & DFS | intuitive-javascript-solution-with-bfs-d-rfwf | \n/**\n * @param {string} beginWord\n * @param {string} endWord\n * @param {string[]} wordList\n * @return {string[][]}\n */\nvar findLadders = function(beginWo | dawchihliou | NORMAL | 2020-04-12T10:25:21.966823+00:00 | 2020-04-12T10:25:21.966862+00:00 | 937 | false | ```\n/**\n * @param {string} beginWord\n * @param {string} endWord\n * @param {string[]} wordList\n * @return {string[][]}\n */\nvar findLadders = function(beginWord, endWord, wordList) {\n if (!wordList.includes(endWord)) {\n return [];\n }\n \n /**\n * Create an adjacency list and run bfs to create a map for \n * verteices with transformation distances.\n * ex: transformation distance for hit -> dot is 2.\n * (two letters transformation) \n *\n * hit\n * | \n * hot\n * / \\\n * dot --- lot\n * | |\n * dog --- log\n * \\ /\n * cog\n */\n const adjacencyList = createAdjacencyList([beginWord, ...wordList]);\n const distances = bfs(beginWord, endWord, adjacencyList);\n /**\n * Use dfs to backtrack all possible paths begin with beginWord. Add \n * all shortest paths to sequences.\n */\n const sequences = [];\n const dfs = (currWord, endWord, path) => {\n if (currWord === endWord) {\n sequences.push([...path]);\n return;\n }\n\n const neighbors = adjacencyList.get(currWord);\n \n neighbors.forEach(neighbor => {\n if (\n distances.has(neighbor) && \n distances.get(neighbor) === distances.get(currWord) + 1\n ) {\n path.push(neighbor);\n dfs(neighbor, endWord, path);\n path.pop();\n }\n });\n }\n dfs(beginWord, endWord, [beginWord]);\n \n return sequences;\n};\n\nfunction createAdjacencyList (words) {\n const adjacencyList = new Map();\n \n words.forEach(word => {\n let adjacentWords = []\n for (let i = 0; i < word.length; i++) {\n const regex = new RegExp(`${word.substring(0, i)}\\\\w${word.substring(i + 1)}`);\n const neighbors = words.filter(w => w !== word && regex.test(w));\n adjacentWords = [...adjacentWords, ...neighbors]\n }\n adjacencyList.set(word, adjacentWords)\n });\n \n return adjacencyList;\n}\n\nfunction bfs(beginWord, endWord, adjacencyList) {\n const distances = new Map()\n const queue = [beginWord];\n let level = 0;\n \n distances.set(beginWord, level);\n \n while(queue.length !== 0) {\n let size = queue.length;\n \n while (size > 0) {\n const word = queue.shift();\n\n if (word === endWord) {\n return distances;\n }\n\n const neighbors = adjacencyList.get(word);\n\n neighbors.forEach(neighbor => {\n if (!distances.has(neighbor)) {\n distances.set(neighbor, level + 1);\n queue.push(neighbor);\n }\n }); \n size -= 1;\n }\n level += 1;\n }\n}\n``` | 5 | 0 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'JavaScript'] | 3 |
word-ladder-ii | C++ - solution accepted - only 1-way BFS with comments. | c-solution-accepted-only-1-way-bfs-with-cblz9 | The solution passes all tests and accepted.\nAppreciate feedback on how to optimize further.\n\n\nclass Solution {\n public:\n /*\n The idea is to | dcbusc2012 | NORMAL | 2019-11-28T07:43:15.079036+00:00 | 2019-11-28T07:43:15.079074+00:00 | 947 | false | The solution passes all tests and accepted.\nAppreciate feedback on how to optimize further.\n\n```\nclass Solution {\n public:\n /*\n The idea is to run a BFS from beginWord to endWord, while keeping track of the path.\n Once the currWord == endWord, we have found the shortest path.\n The nextLevel keeps track of all the words reachable from currLevel.\n All words in nextLevel should be erased from dict to avoid loops.( This is slight modification to the usual BFS ).\n \n */\n vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n unordered_set< string > dict( wordList.begin(), wordList.end() );\n dict.erase( beginWord );\n queue< vector< string > > q;\n vector< vector< string > > result;\n q.push( { beginWord } );\n bool found = false;\n while( !q.empty() ) {\n int size = q.size();\n unordered_set< string > nextLevel;\n\n for( int i = 0 ; i < size ; ++i ) {\n vector< string > currLevel = q.front();\n q.pop();\n string currWord = currLevel.back();\n if( currWord == endWord ) {\n found = true;\n result.push_back( currLevel );\n } else {\n for( int i = 0 ; i < currWord.size() ; ++i ) {\n char orig = currWord[ i ];\n for( char ch = \'a\' ; ch <= \'z\' ; ++ch ) {\n if( ch == orig ) continue;\n currWord[ i ] = ch;\n if( dict.find( currWord ) != dict.end() ) {\n nextLevel.insert( currWord );\n q.push( currLevel );\n q.back().push_back( currWord );\n }\n }\n currWord[ i ] = orig;\n }\n }\n }\n if( found ) break;\n for( auto n : nextLevel ) {\n dict.erase( n );\n }\n }\n return result;\n }\n\n};\n``` | 5 | 0 | ['C++'] | 3 |
minimum-number-of-days-to-disconnect-island | Python [you need at most 2 days] | python-you-need-at-most-2-days-by-gsan-fyec | The tricky part of this question is to notice that, you can disconnect any given island formation in at most 2 days (and you need to convince yourself that this | gsan | NORMAL | 2020-08-30T04:02:58.911391+00:00 | 2024-10-12T10:22:22.584903+00:00 | 10,868 | false | The tricky part of this question is to notice that, you can disconnect any given island formation in at most 2 days (and you need to convince yourself that this is true).\n\n**Day 0:** Check islands at day 0, return 0 if you have less than or greater than one island.\n\n**Day 1**: If not, try to add water at any given location, and check if that gives you a valid island formation.\n\n**Day 2:** Else, just return 2!\n\n```\nimport copy\nclass Solution:\n\t#this is just a helper function for the no_islands function below\n def no_islands_recur(self, grid, i, j, m, n):\n if grid[i][j]==0:\n return\n grid[i][j]=0\n if i-1>=0:\n self.no_islands_recur(grid, i-1, j, m, n)\n if i+1<m:\n self.no_islands_recur(grid, i+1, j, m, n)\n if j-1>=0:\n self.no_islands_recur(grid, i, j-1, m, n)\n if j+1<n:\n self.no_islands_recur(grid, i, j+1, m, n)\n \n\t\n #find how many islands the given grid has \n def no_islands(self, grid):\n ret = 0\n m, n = len(grid), len(grid[0])\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n ret += 1\n self.no_islands_recur(grid, i, j, m, n)\n return ret\n \n \n def minDays(self, grid: List[List[int]]) -> int:\n #if we have 0 or more than 1 islands at day 0, return day 0\n time = 0\n grid_copy = copy.deepcopy(grid)\n n = self.no_islands(grid_copy)\n if n!=1:\n return time\n \n\t\t#try to remove any land any see if it works\n time = 1\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n grid_copy = copy.deepcopy(grid)\n grid_copy[i][j] = 0\n n = self.no_islands(grid_copy)\n if n!=1:\n return time\n \n\t\t#well then just return 2\n time = 2\n return time\n```\n\n | 200 | 3 | ['Python3'] | 35 |
minimum-number-of-days-to-disconnect-island | DFS c++ clean code [with explanation] | dfs-c-clean-code-with-explanation-by-m05-keil | Observation\n## ans <= 2\nans is always less-equal to 2\n## why?\nfor any island we can remove the two blocks around the bottom left corner to make it disconnec | m05s | NORMAL | 2020-08-30T04:02:32.756442+00:00 | 2020-09-01T18:03:45.051353+00:00 | 10,522 | false | # Observation\n## **ans <= 2**\nans is always less-equal to 2\n## **why?**\nfor any island we can remove the two blocks around the bottom left corner to make it disconnected\n```\nx x x\nx . x\nx x x\n```\ncan be changed to\n```\nx x x\nx . .\nx . x\n```\nif you still don\'t get it read this: [comment](https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/discuss/819296/DFS-c++-clean-code-with-explanation/679802)\nwe need to check for only when ans is 1 or 0\n## **ans = 1**\nwe remove a block and check if it disconnects the islands\n## **ans = 0**\nwe check if there are > 1 islands already\n\n```cpp\nclass Solution {\npublic:\n vector<int> dx = {1, -1, 0, 0};\n vector<int> dy = {0, 0, 1, -1};\n void dfs(int x, int y, vector<vector<int>> &grid, vector<vector<int>> & vis)\n {\n int n = grid.size();\n int m = grid[0].size();\n vis[x][y] = 1;\n for (int a = 0; a < 4; a++)\n {\n int nx = x + dx[a];\n int ny = y + dy[a];\n if (nx >= 0 and ny >= 0 and nx < n and ny < m and !vis[nx][ny] and grid[nx][ny])\n {\n dfs(nx, ny, grid, vis);\n }\n }\n }\n int count_islands(vector<vector<int>> & grid)\n {\n int islands = 0;\n int n = grid.size();\n int m = grid[0].size();\n vector<vector<int>> vis(n, vector<int> (m, 0));\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n if (!vis[i][j] and grid[i][j])\n {\n dfs(i, j, grid, vis);\n islands ++;\n }\n }\n }\n return islands;\n }\n int minDays(vector<vector<int>>& grid) {\n int islands = count_islands(grid);\n int n = grid.size();\n int m = grid[0].size();\n\t\t// check for 0 ans\n if (islands > 1 or islands == 0)\n {\n return 0;\n }\n else\n {\n\t\t\t// check for 1 ans\n for (int i = 0 ; i < n; i ++)\n {\n for (int j = 0; j < m; j++)\n {\n if (grid[i][j])\n {\n grid[i][j] = 0;\n\t\t\t\t\t\t// remove this block\n islands = count_islands(grid);\n\t\t\t\t\t\t// add back the block\n grid[i][j] = 1;\n if (islands > 1 or islands == 0)\n return 1;\n }\n\n }\n }\n }\n\t\t// else\n return 2;\n }\n};\n```\n### Time Complexity: O((m*n)^2) | 91 | 3 | [] | 9 |
minimum-number-of-days-to-disconnect-island | Easy to Understand | Step by Step Detailed Explaination | Beginner Friendly | Depth-First Search | easy-to-understand-step-by-step-detailed-fzmv | Problem Statement\nWe are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is defined as a maximal 4-directionally conn | tanishqsingh | NORMAL | 2024-08-11T01:12:07.143842+00:00 | 2024-08-11T01:12:07.143869+00:00 | 27,350 | false | # Problem Statement\nWe are given an `m x n` binary grid `grid` where `1` represents land and `0` represents water. An island is defined as a maximal 4-directionally connected group of `1\'s`. The grid is considered connected if there is exactly one island; otherwise, it is disconnected.\n\nOur task is to determine the minimum number of days required to disconnect the grid by changing any single land cell (`1`) into a water cell (`0`).\n\n# Intuition\nFirst of all, looking at the problem statement, we can observe that we need to make the grid disconnected by turning some land cells into water. If the grid has more than one island initially, it is already disconnected, and no further steps are required. However, if it is connected, we need to figure out the minimum number of days required to disconnect it. So, I decided to use Depth-First Search (DFS) to count the number of islands. If we remove land cells and recheck the number of islands, we can figure out the minimum days needed to achieve a disconnected grid.\n\n# Approach\n### Step 1: **Initial Check for Connectivity**:\n - Before diving into removing any land cells, first, I checked if the grid is already disconnected by counting the number of islands. This was done using a DFS traversal. If the grid is already disconnected (i.e., it has more than one island), then no days are needed, and we can return 0 immediately.\n\n### Step 2: **Try Removing Each Land Cell**:\n - Since the grid might still be connected, I decided to try removing each land cell one by one. For every land cell `(i, j)`, I temporarily changed it to water (`grid[i][j] = 0`) and then rechecked the number of islands using DFS. If the grid becomes disconnected after removing a single cell, it means we only needed one day to achieve this, and I can return 1. If removing a single cell doesn\'t work, I restored the cell back to land (`grid[i][j] = 1`) and moved on to the next cell.\n\n### Step 3: **Handling Cases Where One Day Is Not Enough**:\n - If removing a single land cell is not enough to disconnect the grid, I realized that it would require at least 2 days. This is because a fully connected grid of land cells always needs two changes to disconnect.\n\n### Example\nLet\'s walk through an example with `grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]`:\n\n- **Step 1**:\n - First, I checked if the grid is already disconnected. It was not; the grid had one large island.\n\n- **Step 2**:\n - Then, I began testing each land cell. For instance, by removing the cell at `grid[1][1]`, the grid still remained connected. But when I removed `grid[0][2]`, the grid split into two islands, making it disconnected. So, in this case, I found that it took at least 2 days to disconnect the grid.\n\n# Complexity\n- **Time Complexity**: `O(m * n * (m + n))` where `m` and `n` are the dimensions of the grid. The DFS operation, which checks the number of islands, is run for each cell.\n \n- **Space Complexity**: `O(m * n)` which accounts for the space used by the DFS stack and the grid itself.\n\n# Code\nThis implementation follows the approach I described, ensuring that every step is clear and understandable in a conversational manner.\n\n```C++ []\nclass Solution {\npublic:\n int minDays(vector<vector<int>>& grid) {\n auto count_islands = [&]() -> int {\n vector<vector<int>> seen(grid.size(), vector<int>(grid[0].size(), 0));\n int islands = 0;\n \n function<void(int, int)> dfs = [&](int r, int c) {\n seen[r][c] = 1;\n for (auto [dr, dc] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n int nr = r + dr, nc = c + dc;\n if (nr >= 0 && nr < grid.size() && nc >= 0 && nc < grid[0].size() && grid[nr][nc] == 1 && !seen[nr][nc]) {\n dfs(nr, nc);\n }\n }\n };\n \n for (int i = 0; i < grid.size(); i++) {\n for (int j = 0; j < grid[0].size(); j++) {\n if (grid[i][j] == 1 && !seen[i][j]) {\n islands++;\n dfs(i, j);\n }\n }\n }\n return islands;\n };\n \n if (count_islands() != 1) return 0;\n \n for (int i = 0; i < grid.size(); i++) {\n for (int j = 0; j < grid[0].size(); j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (count_islands() != 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n \n return 2;\n }\n};\n\n```\n\n```Java []\nclass Solution {\n public int minDays(int[][] grid) {\n if (countIslands(grid) != 1) return 0;\n\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (countIslands(grid) != 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n return 2;\n }\n\n private int countIslands(int[][] grid) {\n boolean[][] seen = new boolean[grid.length][grid[0].length];\n int islands = 0;\n\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 1 && !seen[i][j]) {\n islands++;\n dfs(grid, i, j, seen);\n }\n }\n }\n return islands;\n }\n\n private void dfs(int[][] grid, int r, int c, boolean[][] seen) {\n seen[r][c] = true;\n int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n for (int[] dir : directions) {\n int nr = r + dir[0], nc = c + dir[1];\n if (nr >= 0 && nr < grid.length && nc >= 0 && nc < grid[0].length && grid[nr][nc] == 1 && !seen[nr][nc]) {\n dfs(grid, nr, nc, seen);\n }\n }\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n def count_islands():\n seen = set()\n \n def dfs(r, c):\n stack = [(r, c)]\n while stack:\n x, y = stack.pop()\n for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:\n if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == 1 and (nx, ny) not in seen:\n seen.add((nx, ny))\n stack.append((nx, ny))\n \n islands = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1 and (i, j) not in seen:\n islands += 1\n seen.add((i, j))\n dfs(i, j)\n return islands\n \n if count_islands() != 1:\n return 0\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n grid[i][j] = 0\n if count_islands() != 1:\n return 1\n grid[i][j] = 1\n \n return 2\n\n\n```\n```JavaScript []\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minDays = function(grid) {\n const countIslands = () => {\n const seen = new Set();\n let islands = 0;\n\n const dfs = (r, c) => {\n const stack = [[r, c]];\n while (stack.length > 0) {\n const [x, y] = stack.pop();\n for (const [dx, dy] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) {\n const nx = x + dx, ny = y + dy;\n if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] === 1 && !seen.has(`${nx},${ny}`)) {\n seen.add(`${nx},${ny}`);\n stack.push([nx, ny]);\n }\n }\n }\n };\n\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (grid[i][j] === 1 && !seen.has(`${i},${j}`)) {\n islands++;\n seen.add(`${i},${j}`);\n dfs(i, j);\n }\n }\n }\n return islands;\n };\n\n if (countIslands() !== 1) return 0;\n\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0;\n if (countIslands() !== 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n return 2;\n};\n\n\n```\nThank you for exploring this solution! I hope it helped clarify the problem. \n### Please feel free to upvote if you found it useful. Happy coding!\n\n | 88 | 2 | ['Depth-First Search', 'Graph', 'C++', 'Java', 'Python3', 'JavaScript'] | 8 |
minimum-number-of-days-to-disconnect-island | ✅Beats 100% -Explained with [ Video ] -C++/Java - DFS - Explained in Detail | beats-100-explained-with-video-cjava-dfs-s21z | \n\n# YouTube Video Explanation:\n\n ### To watch the video please click on "Watch On Youtube" option available the left bottom corner of the thumbnail. \n\nIf | lancertech6 | NORMAL | 2024-08-11T00:44:06.206178+00:00 | 2024-08-11T00:44:06.206202+00:00 | 8,948 | false | \n\n# YouTube Video Explanation:\n\n<!-- ### To watch the video please click on "Watch On Youtube" option available the left bottom corner of the thumbnail. -->\n\n**If you want a video for this question please write in the comments**\n\n\n<!-- https://youtu.be/JYw3FE3JisQ -->\n\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 2800 Subscribers*\n*Current Subscribers: 2733*\n\nFollow me on Instagram : https://www.instagram.com/divyansh.nishad/\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks us to find the minimum number of days required to disconnect an initially connected island in a binary grid. An island is considered "disconnected" if there are two or more separate islands or no islands at all. To solve this problem, we can use a combination of depth-first search (DFS) and Tarjan\'s algorithm for finding articulation points in a graph. An articulation point is a vertex which, when removed, increases the number of connected components in the graph.\n\nHere\u2019s the main intuition:\n1. **Day 0:** If the grid is already disconnected, return `0`.\n2. **Day 1:** If we can disconnect the grid by removing just one cell, we return `1`.\n3. **Day 2:** If the grid cannot be disconnected in one move, it can always be disconnected in two moves because any grid with more than one cell will always have at least two different land cells that can be removed to disconnect it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Check if Grid is Already Disconnected (Day 0):** \n - Perform a DFS or BFS from any land cell to see if all land cells are connected.\n - If the grid is already disconnected, return `0`.\n\n2. **Find Articulation Points:**\n - If the grid is connected, find the articulation points using DFS. Articulation points are critical cells; if removed, they will disconnect the grid.\n - Use Tarjan\u2019s algorithm to identify articulation points. If we find any articulation point, return `1` because removing it will immediately disconnect the island.\n\n3. **Return 2 for the General Case:** \n - If there are no articulation points, it means the grid can only be disconnected by removing two or more cells. Therefore, return `2`.\n\n# Complexity\n- **Time Complexity:** \n - The DFS runs in `O(V + E)` time, where `V` is the number of vertices (land cells) and `E` is the number of edges (connections between land cells). In the worst case, `V` and `E` can be up to `O(m * n)`, where `m` and `n` are the dimensions of the grid.\n - Thus, the overall time complexity is `O(m * n)`.\n\n- **Space Complexity:**\n - The space complexity is also `O(m * n)` due to the recursive stack in DFS and the arrays used for storing visited nodes and low-link values.\n\n# Step By Step Explanation\n\n\n### Step 1: Understanding the Grid and the Problem\n- **Grid**: The grid is an `m x n` matrix where `1` represents land and `0` represents water.\n- **Goal**: Determine the minimum number of days to disconnect the grid, meaning to make the grid such that there is no single connected island of land.\n\n### Step 2: Initialization\n- **Visitation and Low Tables**:\n - `vis[row][col]`: Stores the visitation time (DFS discovery time) of each cell during traversal.\n - `low[row][col]`: Stores the lowest discovery time reachable from the cell, including back edges.\n\n**Example Grid:**\n```plaintext\n[ [0, 1, 1, 0],\n [0, 1, 1, 0],\n [0, 0, 0, 0] ]\n```\n\n**Tables Initialization:**\n| Cell (i,j) | vis[i][j] | low[i][j] | Remarks |\n|------------|-----------|-----------|---------------------------|\n| (0,0) | 0 | 0 | Water cell, unvisited |\n| (0,1) | 0 | 0 | Land cell, unvisited |\n| (0,2) | 0 | 0 | Land cell, unvisited |\n| (0,3) | 0 | 0 | Water cell, unvisited |\n| (1,0) | 0 | 0 | Water cell, unvisited |\n| (1,1) | 0 | 0 | Land cell, unvisited |\n| (1,2) | 0 | 0 | Land cell, unvisited |\n| (1,3) | 0 | 0 | Water cell, unvisited |\n| (2,0) | 0 | 0 | Water cell, unvisited |\n| (2,1) | 0 | 0 | Water cell, unvisited |\n| (2,2) | 0 | 0 | Water cell, unvisited |\n| (2,3) | 0 | 0 | Water cell, unvisited |\n\n### Step 3: Depth-First Search (DFS) and Articulation Point Detection\n- **DFS Traversal**: Start traversing the grid from the first unvisited land cell (`1`), and update `vis` and `low` values.\n\n**DFS Example:**\n\nLet\'s consider DFS starting at cell (0,1).\n\n1. **Visiting Cell (0,1)**:\n - Set `vis[0][1] = 1`, `low[0][1] = 1`\n \n| Cell (i,j) | vis[i][j] | low[i][j] | Remarks |\n|------------|-----------|-----------|----------------------------------|\n| (0,1) | 1 | 1 | Start DFS, discovery time = 1 |\n\n2. **Visiting Neighbor Cell (1,1)**:\n - Set `vis[1][1] = 2`, `low[1][1] = 2`\n \n| Cell (i,j) | vis[i][j] | low[i][j] | Remarks |\n|------------|-----------|-----------|----------------------------------|\n| (1,1) | 2 | 2 | DFS continues to (1,1) |\n\n3. **Visiting Neighbor Cell (1,2)**:\n - Set `vis[1][2] = 3`, `low[1][2] = 3`\n \n| Cell (i,j) | vis[i][j] | low[i][j] | Remarks |\n|------------|-----------|-----------|----------------------------------|\n| (1,2) | 3 | 3 | DFS continues to (1,2) |\n\n4. **Visiting Neighbor Cell (0,2)**:\n - Set `vis[0][2] = 4`, `low[0][2] = 4`\n \n| Cell (i,j) | vis[i][j] | low[i][j] | Remarks |\n|------------|-----------|-----------|----------------------------------|\n| (0,2) | 4 | 4 | DFS continues to (0,2) |\n\n5. **Backtrack and Update `low` Values**:\n - As we backtrack from (0,2), update `low[1][2]`, `low[1][1]`, and `low[0][1]` based on their neighbors\' `low` values.\n\n### Step 4: Check for Articulation Points\n- **Articulation Point**: A cell that, if removed, increases the number of connected components (islands).\n- **Check**: After DFS, check if any cell is an articulation point.\n - If found, disconnect the grid by removing that cell.\n\n**Final Tables after DFS:**\n\n| Cell (i,j) | vis[i][j] | low[i][j] | Articulation Point? |\n|------------|-----------|-----------|--------------------------------|\n| (0,1) | 1 | 1 | Yes |\n| (1,1) | 2 | 2 | No |\n| (1,2) | 3 | 3 | Yes |\n| (0,2) | 4 | 4 | No |\n\n### Step 5: Determine the Minimum Days\n- **Decision**: Based on the articulation points, determine the minimum number of days to disconnect the grid.\n - **If there is no articulation point**: It takes 2 days to disconnect.\n - **If there is exactly one articulation point**: It takes 1 day to disconnect.\n - **If the grid is already disconnected or fully water**: It takes 0 days.\n\n**Example Summary**:\n- For the given grid, it takes **2 days** to disconnect by changing the land cells at (1,1) and (0,2) to water.\n\n\n# Code\n```java []\nclass Solution {\n int time;\n int[][] vis;\n int[][] low;\n int[] d=new int[]{0,1,0,-1,0};\n boolean arti;\n public int minDays(int[][] grid) {\n int n=grid.length;\n int m=grid[0].length;\n arti=false;\n vis=new int[n][m];\n low=new int[n][m];\n time=1;\n boolean hasArt=false;\n boolean found=false;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1){\n if(found)\n return 0;\n found=true;\n art(i,j,grid,-100,-100);\n }\n }\n }\n\n if(time==1)\n return 0;\n\n if(time==2)\n return 1;\n if(arti)\n return 1;\n else\n return 2;\n }\n\n public void art(int row,int col,int[][] grid , int parRow,int parCol){\n grid[row][col]=0;\n vis[row][col]=time;\n low[row][col]=time;\n time++;\n int child=0;\n for(int i=0;i<4;i++){\n int x=d[i]+row;\n int y=d[i+1]+col;\n\n if(x<0 || y<0 || x>=grid.length || y>=grid[0].length || (x==parRow && y==parCol) || (vis[x][y]==0 && grid[x][y]==0))\n continue;\n if(vis[x][y]==0){\n child++;\n art(x,y,grid,row,col);\n low[row][col]=Math.min(low[row][col],low[x][y]);\n if(low[x][y]>=vis[row][col] && (parRow!=-100 && parCol!=-100))\n arti=true;\n }else{\n low[row][col]=Math.min(low[row][col],vis[x][y]);\n }\n }\n\n if(parRow==-100 && parCol==-100 && child>1)\n arti=true;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int time;\n vector<vector<int>> vis;\n vector<vector<int>> low;\n int d[5] = {0, 1, 0, -1, 0};\n bool arti;\n \n int minDays(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n arti = false;\n vis = vector<vector<int>>(n, vector<int>(m, 0));\n low = vector<vector<int>>(n, vector<int>(m, 0));\n time = 1;\n bool hasArt = false;\n bool found = false;\n \n for(int i = 0; i < n; ++i) {\n for(int j = 0; j < m; ++j) {\n if(grid[i][j] == 1) {\n if(found)\n return 0;\n found = true;\n art(i, j, grid, -100, -100);\n }\n }\n }\n\n if(time == 1)\n return 0;\n\n if(time == 2)\n return 1;\n if(arti)\n return 1;\n else\n return 2;\n }\n\n void art(int row, int col, vector<vector<int>>& grid, int parRow, int parCol) {\n grid[row][col] = 0;\n vis[row][col] = time;\n low[row][col] = time;\n time++;\n int child = 0;\n for(int i = 0; i < 4; ++i) {\n int x = d[i] + row;\n int y = d[i+1] + col;\n\n if(x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || (x == parRow && y == parCol) || (vis[x][y] == 0 && grid[x][y] == 0))\n continue;\n if(vis[x][y] == 0) {\n child++;\n art(x, y, grid, row, col);\n low[row][col] = min(low[row][col], low[x][y]);\n if(low[x][y] >= vis[row][col] && (parRow != -100 && parCol != -100))\n arti = true;\n } else {\n low[row][col] = min(low[row][col], vis[x][y]);\n }\n }\n\n if(parRow == -100 && parCol == -100 && child > 1)\n arti = true;\n }\n};\n```\n\n | 61 | 6 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'Strongly Connected Component', 'C++', 'Java'] | 4 |
minimum-number-of-days-to-disconnect-island | [Java] Easy to understand | java-easy-to-understand-by-mayank12559-ebub | \nclass Solution {\n public int minDays(int[][] grid) {\n if(noOfIsland(grid) != 1){\n return 0;\n }\n for(int i=0;i<grid.len | mayank12559 | NORMAL | 2020-08-30T04:08:50.626967+00:00 | 2020-08-30T04:08:50.627011+00:00 | 3,068 | false | ```\nclass Solution {\n public int minDays(int[][] grid) {\n if(noOfIsland(grid) != 1){\n return 0;\n }\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[0].length;j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n if(noOfIsland(grid) != 1){\n return 1;\n }\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n \n private int noOfIsland(int [][]grid){\n int ans = 0;\n boolean [][]visited = new boolean[grid.length][grid[0].length];\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[0].length;j++){\n if(!visited[i][j] && grid[i][j] == 1){\n ans ++;\n dfs(visited, grid,i,j);\n }\n }\n }\n return ans;\n }\n \n private void dfs(boolean [][]visited, int [][]grid,int i, int j){\n if(i < 0 || j < 0 || i == grid.length || j == grid[0].length || visited[i][j] || grid[i][j] == 0){\n return ;\n }\n visited[i][j] = true;\n dfs(visited, grid, i-1, j);\n dfs(visited, grid, i+1, j);\n dfs(visited, grid, i, j-1);\n dfs(visited, grid, i, j+1);\n }\n}\n``` | 38 | 1 | [] | 4 |
minimum-number-of-days-to-disconnect-island | ✅ Easy 3 step C++/ Java / Py / JS Solution | DFS | With Visualization🏆| | easy-3-step-c-java-py-js-solution-dfs-wi-qpj5 | Steps:\n1. Check if the Grid is Already Disconnected:\n - Use a function to count the number of islands in the grid.\n - If there is already more than one i | dev_yash_ | NORMAL | 2024-08-11T01:28:25.878442+00:00 | 2024-08-11T03:43:12.339586+00:00 | 4,050 | false | ### Steps:\n1. **Check if the Grid is Already Disconnected:**\n - Use a function to count the number of islands in the grid.\n - If there is already more than one island, the grid is disconnected, so return `0` days.\n\n2. **Try Removing One Land Cell:**\n - Iterate over each land cell in the grid.\n - For each land cell, temporarily set it to water and check if this disconnection results in more than one island.\n - If removing one cell is sufficient to disconnect the grid, return `1` day.\n\n3. **If Removing One Cell Isn\u2019t Enough, Return 2:**\n - If removing one land cell doesn\u2019t disconnect the grid, then it is guaranteed that removing any two land cells will disconnect the grid.\n - Therefore, if neither of the above conditions is met, return `2` days.\n\n\n ### **Iteration Visualization** : (Credit-GPT)\n\n\n#### **1. Check if the Grid is Already Disconnected**\n\n**Initial Grid Example:**\n0 1 1 0\n0 1 1 0\n0 0 0 0\n\n\n - **Action:** Use a function to count the number of islands.\n - **Count:** There is 1 island.\n - **Result:** The grid is connected, so proceed to the next step.\n\n#### **2. Try Removing One Land Cell**\n\n- **Iteration 1: Removing Cell `(0,1)`**\n\n **After Removal:**\n \n 0 0 1 0\n 0 1 1 0\n 0 0 0 0\n \n \n- **Count:** Still 1 island (since removing one cell didn\u2019t disconnect the island).\n\n- **Iteration 2: Removing Cell `(0,2)`**\n\n **After Removal:**\n 0 1 0 0\n0 1 1 0\n0 0 0 0\n\n\n- **Count:** Still 1 island.\n\n- **Iteration 3: Removing Cell `(1,1)`**\n\n **After Removal:**\n0 1 1 0\n0 0 1 0\n0 0 0 0\n\n\n- **Count:** Still 1 island.\n\n- **Iteration 4: Removing Cell `(1,2)`**\n\n **After Removal:**\n0 1 1 0\n0 1 0 0\n0 0 0 0\n\n\n- **Count:** Still 1 island.\n\nSince removing one cell does not disconnect the grid, we need to check removing two cells.\n\n#### **3. If Removing One Cell Isn\u2019t Enough, Return 2**\n\n- **Try Removing Two Land Cells**\n\n **Remove `(0,1)` and `(0,2)`**\n\n **After Removal:**\n0 0 0 0\n0 1 1 0\n0 0 0 0\n\n\n- **Count:** 2 islands (disconnected).\n\n- **Another Combination: Remove `(1,1)` and `(1,2)`**\n\n **After Removal:**\n0 1 1 0\n0 0 0 0\n0 0 0 0\n- **Count:** 2 islands (disconnected).\n\n\n\n\n\n\n\n\n### C++\n```\n//More Optimized\nclass Solution {\npublic:\n // A helper function to perform Depth-First Search (DFS) to explore the island\n void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int i, int j) {\n int m = grid.size(), n = grid[0].size();\n // Check boundaries and whether the cell is already visited or is water\n if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0 || visited[i][j])\n return;\n visited[i][j] = true; // Mark the cell as visited\n // Recursively visit all 4 directions\n dfs(grid, visited, i+1, j);\n dfs(grid, visited, i-1, j);\n dfs(grid, visited, i, j+1);\n dfs(grid, visited, i, j-1);\n }\n\n // Function to count the number of islands (connected groups of 1\'s)\n int countIslands(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n vector<vector<bool>> visited(m, vector<bool>(n, false));\n int count = 0;\n\n // Iterate through the grid to find and count each island\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n // If we find a land cell that is not visited, start a new DFS\n if (grid[i][j] == 1 && !visited[i][j]) {\n count++;\n dfs(grid, visited, i, j); // Explore the island\n }\n }\n }\n return count;\n }\n \n // Function to determine the minimum number of days to disconnect the island\n int minDays(vector<vector<int>>& grid) {\n // Step 1: Check if the grid is already disconnected\n if (countIslands(grid) != 1) return 0;\n \n int m = grid.size(), n = grid[0].size();\n\n // Step 2: Try removing one land cell\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0; // Remove the land cell\n // Check if removing this cell disconnects the grid\n if (countIslands(grid) != 1) return 1;\n grid[i][j] = 1; // Restore the land cell\n }\n }\n }\n\n // Step 3: If removing one cell isn\'t enough, return 2 (as it is guaranteed to be sufficient)\n return 2;\n }\n};\n\n```\n### Java\n```\n class Solution {\n // Helper function to perform Depth-First Search (DFS) to explore the island\n private void dfs(int[][] grid, boolean[][] visited, int i, int j) {\n int m = grid.length, n = grid[0].length;\n // Check boundaries and whether the cell is already visited or is water\n if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0 || visited[i][j]) \n return;\n visited[i][j] = true; // Mark the cell as visited\n // Recursively visit all 4 directions\n dfs(grid, visited, i + 1, j);\n dfs(grid, visited, i - 1, j);\n dfs(grid, visited, i, j + 1);\n dfs(grid, visited, i, j - 1);\n }\n\n // Function to count the number of islands (connected groups of 1\'s)\n private int countIslands(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n boolean[][] visited = new boolean[m][n];\n int count = 0;\n\n // Iterate through the grid to find and count each island\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // If we find a land cell that is not visited, start a new DFS\n if (grid[i][j] == 1 && !visited[i][j]) {\n count++;\n dfs(grid, visited, i, j); // Explore the island\n }\n }\n }\n return count;\n }\n \n // Function to determine the minimum number of days to disconnect the island\n public int minDays(int[][] grid) {\n // Step 1: Check if the grid is already disconnected\n if (countIslands(grid) != 1) \n return 0;\n \n int m = grid.length, n = grid[0].length;\n\n // Step 2: Try removing one land cell\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0; // Remove the land cell\n // Check if removing this cell disconnects the grid\n if (countIslands(grid) != 1) \n return 1;\n grid[i][j] = 1; // Restore the land cell\n }\n }\n }\n\n // Step 3: If removing one cell isn\'t enough, return 2 (as it is guaranteed to be sufficient)\n return 2;\n }\n}\n\n\n```\n\n### Python3\n```\n\nclass Solution:\n # Helper function to perform Depth-First Search (DFS) to explore the island\n def dfs(self, grid: List[List[int]], visited: List[List[bool]], i: int, j: int):\n m, n = len(grid), len(grid[0])\n # Check boundaries and whether the cell is already visited or is water\n if i < 0 or j < 0 or i >= m or j >= n or grid[i][j] == 0 or visited[i][j]:\n return\n visited[i][j] = True # Mark the cell as visited\n # Recursively visit all 4 directions\n self.dfs(grid, visited, i+1, j)\n self.dfs(grid, visited, i-1, j)\n self.dfs(grid, visited, i, j+1)\n self.dfs(grid, visited, i, j-1)\n\n # Function to count the number of islands (connected groups of 1\'s)\n def countIslands(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n visited = [[False] * n for _ in range(m)]\n count = 0\n\n # Iterate through the grid to find and count each island\n for i in range(m):\n for j in range(n):\n # If we find a land cell that is not visited, start a new DFS\n if grid[i][j] == 1 and not visited[i][j]:\n count += 1\n self.dfs(grid, visited, i, j) # Explore the island\n return count\n \n # Function to determine the minimum number of days to disconnect the island\n def minDays(self, grid: List[List[int]]) -> int:\n # Step 1: Check if the grid is already disconnected\n if self.countIslands(grid) != 1:\n return 0\n \n m, n = len(grid), len(grid[0])\n\n # Step 2: Try removing one land cell\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n grid[i][j] = 0 # Remove the land cell\n # Check if removing this cell disconnects the grid\n if self.countIslands(grid) != 1:\n return 1\n grid[i][j] = 1 # Restore the land cell\n\n # Step 3: If removing one cell isn\'t enough, return 2 (as it is guaranteed to be sufficient)\n return 2\n\n```\n### JavaScript\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minDays = function(grid) {\n // Helper function to perform Depth-First Search (DFS) to explore the island\n function dfs(grid, visited, i, j) {\n const m = grid.length, n = grid[0].length;\n // Check boundaries and whether the cell is already visited or is water\n if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] === 0 || visited[i][j]) return;\n visited[i][j] = true; // Mark the cell as visited\n // Recursively visit all 4 directions\n dfs(grid, visited, i + 1, j);\n dfs(grid, visited, i - 1, j);\n dfs(grid, visited, i, j + 1);\n dfs(grid, visited, i, j - 1);\n }\n\n // Function to count the number of islands (connected groups of 1\'s)\n function countIslands(grid) {\n const m = grid.length, n = grid[0].length;\n const visited = Array.from({ length: m }, () => Array(n).fill(false));\n let count = 0;\n\n // Iterate through the grid to find and count each island\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n // If we find a land cell that is not visited, start a new DFS\n if (grid[i][j] === 1 && !visited[i][j]) {\n count++;\n dfs(grid, visited, i, j); // Explore the island\n }\n }\n }\n return count;\n }\n \n // Function to determine the minimum number of days to disconnect the island\n if (countIslands(grid) !== 1) return 0;\n \n const m = grid.length, n = grid[0].length;\n\n // Step 2: Try removing one land cell\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0; // Remove the land cell\n // Check if removing this cell disconnects the grid\n if (countIslands(grid) !== 1) return 1;\n grid[i][j] = 1; // Restore the land cell\n }\n }\n }\n\n // Step 3: If removing one cell isn\'t enough, return 2 (as it is guaranteed to be sufficient)\n return 2;\n};\n\n\n```\n#### STAY COOL STAY DISCIPLINED..\n\n | 26 | 1 | ['Depth-First Search', 'Breadth-First Search', 'Graph', 'C', 'Java', 'Python3', 'JavaScript'] | 9 |
minimum-number-of-days-to-disconnect-island | [Python / Golang] There are only 3 possible answers! | python-golang-there-are-only-3-possible-ocm9j | \n## Idea\nHow to make the grid disconnected?\nWe can tell from the first official example that, the worst situation we may get into is to take 2 steps and sepa | yanrucheng | NORMAL | 2020-08-30T04:00:49.247784+00:00 | 2020-08-30T04:09:59.738439+00:00 | 2,744 | false | \n## Idea\n**How to make the grid disconnected?**\nWe can tell from the first official example that, the worst situation we may get into is to take 2 steps and separate a single island out.\nMore specifically, there are 3 situation.\n1. The number of island on the grid is not 1.\n\t- return 0\n1. The number of island on the grid is 1, and we can break them into 2 islands within 1 step.\n\t- return 1\n1. The number of island on the grid is 1, and we cannot break them into 2 islands within 1 step.\n\t- return 2, because no matter what, we can always separate 1 island out within 2 steps\n\n\n**How to count the number of islands on the grid**\nThere are many different ways like DFS, Union Find. I use union find here.\n\n## Complexity\n- Time: O(n^4)\n- Space: O(n^2)\n\n## Python\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n def countIsland():\n roots = {(i,j):(i,j) for i in range(m) for j in range(n)}\n def find(i):\n if roots[i] != i: roots[i] = find(roots[i])\n return roots[i] \n \n def unite(i, j):\n roots[find(i)] = find(j)\n \n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n if i < m - 1 and grid[i + 1][j]:\n unite((i, j), (i + 1, j))\n if j < n - 1 and grid[i][j + 1]:\n unite((i, j), (i, j + 1))\n return len(set(find((i, j)) for i in range(m) for j in range(n) if grid[i][j])) \n \n if countIsland() != 1:\n return 0\n \n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n grid[i][j] = 0\n if countIsland() != 1:\n return 1\n grid[i][j] = 1\n return 2\n```\n\n## Golang\n```\nimport "fmt"\n\nfunc minDays(grid [][]int) int {\n if countIslands(grid) != 1 {\n return 0\n }\n for i := range grid {\n for j := range grid[0] {\n if grid[i][j] == 1 {\n grid[i][j] = 0\n if countIslands(grid) != 1 {\n return 1\n }\n grid[i][j] = 1\n }\n }\n }\n return 2\n}\n\nvar roots [][][2]int\n\nfunc countIslands(grid [][]int) int {\n m, n := len(grid), len(grid[0])\n roots = make([][][2]int, m)\n for i := range grid {\n roots[i] = make([][2]int, n)\n for j := range roots[i] {\n roots[i][j] = [2]int {i, j}\n }\n }\n \n for i := range grid {\n for j := range grid[0] {\n if grid[i][j] == 1 {\n if i < m - 1 && grid[i + 1][j] == 1 {\n unite(i, j, i + 1, j)\n }\n if j < n - 1 && grid[i][j + 1] == 1 {\n unite(i, j, i, j + 1)\n }\n }\n }\n }\n set := make(map[int]bool)\n for i := range grid {\n for j := range grid[0] {\n if grid[i][j] == 1 {\n tmp := find(i, j)\n set[tmp[0] * n + tmp[1]] = true\n }\n }\n }\n return len(set)\n}\n\nfunc find(i, j int) [2]int {\n if roots[i][j] != [2]int {i, j} {\n tmp := roots[i][j]\n roots[i][j] = find(tmp[0], tmp[1])\n }\n return roots[i][j]\n}\n\nfunc unite(xi, xj, yi, yj int) {\n x := find(xi, xj)\n roots[x[0]][x[1]] = find(yi, yj)\n}\n``` | 25 | 2 | [] | 8 |
minimum-number-of-days-to-disconnect-island | C++ At most 2 removal; Try removing each one and see if the graph is disconnected. | c-at-most-2-removal-try-removing-each-on-q71u | See my latest update in repo LeetCode\n\n## Solution 1.\n\nYou need at most two days to separate out a 1 at the corner with all other 1s. So the answer is one o | lzl124631x | NORMAL | 2020-08-30T04:30:15.418062+00:00 | 2020-08-30T19:19:59.782215+00:00 | 2,568 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1.\n\nYou need at most two days to separate out a `1` at the corner with all other `1`s. So the answer is one of `0`, `1`, `2`.\n\nIf the graph is already disconnected, return `0`.\n\nFor each `1`, see if removing it can disconnect the graph. If yes, then return `1`.\n\nOtherwise return `2`.\n\n```cpp\n// OJ: https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/\n// Author: github.com/lzl124631x\n// Time: O((MN)^2)\n// Space: O(MN)\nclass Solution {\n int M, N, dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};\n void dfs(vector<vector<int>> &G, int i, int j,vector<vector<int>> &seen) {\n seen[i][j] = true;\n for (auto &[dx, dy] : dirs) {\n int x = dx + i, y = dy + j;\n if (x < 0 || x >= M || y < 0 || y >= N || G[x][y] != 1 || seen[x][y]) continue;\n dfs(G, x, y, seen);\n }\n }\n bool disconnected(vector<vector<int>> &G) {\n vector<vector<int>> seen(M, vector<int>(N, false));\n int cnt = 0;\n for (int i = 0; i < M; ++i) {\n for (int j = 0; j < N; ++j) {\n if (G[i][j] != 1 || seen[i][j]) continue;\n if (++cnt > 1) return true;\n dfs(G, i, j, seen);\n }\n }\n return cnt == 0;\n }\npublic:\n int minDays(vector<vector<int>>& G) {\n M = G.size(), N = G[0].size();\n if (disconnected(G)) return 0;\n for (int i = 0; i < M; ++i) {\n for (int j = 0; j < N; ++j) {\n if (G[i][j] != 1) continue;\n G[i][j] = 0;\n if (disconnected(G)) return 1;\n G[i][j] = 1;\n }\n }\n return 2;\n }\n};\n``` | 20 | 0 | [] | 3 |
minimum-number-of-days-to-disconnect-island | Most Optimal Approach (Articulation Point) || TC: O(n * m) | most-optimal-approach-articulation-point-j8hd | Intuition\n1. If there are no islands or more than 1 island, than the answer is 0, as we don\'t need to remove anything.\n2. If we can disconnct the island by r | WeirdLogic | NORMAL | 2023-11-29T19:02:52.404848+00:00 | 2023-11-29T19:05:05.741489+00:00 | 1,196 | false | # Intuition\n1. If there are no islands or more than 1 island, than the answer is 0, as we don\'t need to remove anything.\n2. If we can disconnct the island by removing exactly 1 cell, the answer is 1 (will be explaining it shortly in Case 2 of **Approach**).\n3. At last, we can always disconnect an island by removing exactly 2 cells. (see Case 3 in **Approach**).\n \n\n# Approach\nTo make the implementation simple, let\'s build a graph from the grid.\nFor every land cell[i, j], add it to graph with $$id = (M * i + j)$$, where $$M = grid[0].size()$$. Also check it\'s 4 neighbouring cells and add an edge between the current cell and ***neighbour[r, c]*** if ***neighbour[r, c]*** is also a land cell.\n\n**Case 1** is easy to handle, just check for the number of connected components, if they are > 1, the answer is zero, or if the number of vertices in graph is 1, then answer is 1.\n\n**Case 2** is the bottleneck in all other solutions. One simple observation is that if the graph that we have created has any articulation point, then we can remove this articulation point and the island will get disconnected (that\'s what an articulation point really means). So the answer is 1, if there exists atleast 1 articulation point in the graph.\n\n\nHere, 5 is an articulation point. Removing 5 will isolate 8, so the answer is 1.\n\n**Case 3** is the last option that we have. we can always disconnect an island by removing exactly 2 cells. See the below example.\n\n\nWe can remove vertices 2 and 4, which will isolate vertex 1\nWe can remove vertices 2 and 6, which will isolate vertex 3\nWe can remove vertices 4 and 8, which will isolate vertex 7\nWe can remove vertices 6 and 8, which will isolate vertex 9\n\nSo picking any of these pairs is fine. Also, it can be easily shown that there always exist atleast 1 such pair which will break the island into 2 components.\n\n# Complexity\n- Time complexity: O(N * M)\n\n- Space complexity: O(N * M)\n\n# Code\n```\nclass Solution {\n const vector<int> delta = {-1, 0, 1, 0};\n unordered_map<int, int> low, tin;\n int timer = 0;\n bool articulation_point = false;\n\n void dfs(unordered_map<int, vector<int>> &adj, int u, int par) {\n low[u] = tin[u] = ++timer;\n int child_count = 0;\n for(int v: adj[u])\n if(v != par) {\n if(low.count(v)) {\n low[u] = min(low[u], tin[v]);\n } else {\n child_count++;\n dfs(adj, v, u);\n if(low[v] >= tin[u] && par != -1) {\n articulation_point = true;\n }\n low[u] = min(low[u], low[v]);\n }\n }\n if(par == -1 && child_count > 1)\n articulation_point = true;\n }\n\npublic:\n int minDays(vector<vector<int>>& grid) {\n const int n = grid.size(), m = grid[0].size();\n const int V = n * m;\n unordered_map<int, vector<int>> adj;\n int vertex_count = 0;\n for(int i = 0; i < n; i++)\n for(int j = 0; j < m; j++)\n if(grid[i][j]) {\n int id = i * m + j;\n adj[id] = {};\n for(int k = 0; k < 4; k++) {\n int r = i + delta[k], c = j + delta[(k+1) % 4]; //smart way to iterate over all 4 neighbours\n if(r < n && c < m && r >= 0 && c >= 0 && grid[r][c]) {\n int id_adj = r * m + c;\n adj[id].push_back(id_adj);\n }\n }\n }\n \n if(adj.size() <= 1)\n return adj.size();\n\n bool multiple_dfs = 0;\n for(auto &it: adj)\n if(!low.count(it.first)) {\n if(multiple_dfs)\n return 0;\n dfs(adj, it.first, -1);\n multiple_dfs = 1;\n }\n\n if(articulation_point)\n return 1;\n \n return 2;\n }\n};\n``` | 18 | 0 | ['Depth-First Search', 'Graph', 'C++'] | 2 |
minimum-number-of-days-to-disconnect-island | DFS + test vertices if any neighbor with deg<=2||7ms Beats 93.10% | dfs-test-vertices-if-any-neighbor-with-d-lydd | Intuition\n Describe your first thoughts on how to solve this problem. \nNot optimal, but much better than brute force.\n\nJust consider the vertices with degre | anwendeng | NORMAL | 2024-08-11T08:18:33.808770+00:00 | 2024-08-11T08:36:50.688940+00:00 | 1,326 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNot optimal, but much better than brute force.\n\nJust consider the vertices with degree<=2 & its all adjacent vertices.\n\nA vertex here is a cell with 1. A vertex has at most 4 adjacent vertices.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use array `deg[30][30]` which is multipurposed, 1 as marking as visited, more important keep the degree info\n2. Define `dfs0` to transverse the path-connected cells.\n3. Define the function `component` to compute the number of components in grid\n4. According to hints, the answer can be either 0, 1, or 2\n5. First application for `component` will be known if ans=0 or not.\n6. Using loop to find the vertices with deg<=2 and all its adjacent vertices. Using the container `deg2` to store them.\n7. Test all vertices in `deg2` to find either ans=1 or ans=2.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(rc\\cdot |cells\\ with\\ \\deg<=2|)$$ \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(rc+ |cells\\ with\\ \\deg<=2|)$\n# Code||C++ 7ms Beats 93.10%\n```\nclass Solution {\npublic:\n int r, c;\n int d[5] = {0, 1, 0, -1, 0};\n char deg[30][30];// degree -1~4\n\n inline bool inside(int i, int j) { return 0<=i && i<r && 0<=j && j<c;}\n\n inline void dfs0(int i, int j, vector<vector<int>>& grid) {\n deg[i][j] = 0;\n for (int a = 0; a < 4; a++) {\n int s = i + d[a], t = j + d[a + 1];\n if (inside(s, t) && grid[s][t] == 1) {\n deg[i][j]++;\n if (deg[s][t]==-1)\n dfs0(s, t, grid);\n } \n }\n // cout<<i<<","<<j<<","<<(int)deg[i][j]<<endl;\n }\n\n inline int component(vector<vector<int>>& grid) {\n int cnt=0;\n for (int i = 0; i < r; i++) {\n for (int j = 0; j < c; j++) {\n if (grid[i][j] == 1 && deg[i][j]==-1) {\n cnt++;\n dfs0(i, j, grid);\n }\n }\n }\n return cnt;\n }\n\n int minDays(vector<vector<int>>& grid) {\n r = grid.size(), c = grid[0].size();\n\n memset(deg, -1, sizeof(deg));\n\n int cnt = component(grid);\n if (cnt!=1) return 0;\n\n vector<pair<char, char>> deg2;\n\n bitset<30> seen[30] = {0};\n for (int i = 0; i < r; i++){\n for (int j = 0; j < c; j++){\n // cout<<i<<","<<j<<","<<(int)deg[i][j]<<endl;\n if (deg[i][j]>=0 && deg[i][j] <= 2) {\n if (!seen[i][j]){\n deg2.push_back({i, j});\n seen[i][j]=1;\n }\n for (int a = 0; a < 4; a++) {\n int s = i + d[a], t = j + d[a + 1];\n if (inside(s, t) && grid[s][t]==1 && !seen[s][t]) {\n deg2.push_back({s, t});\n seen[s][t] = 1;\n }\n }\n }\n }\n\n }\n \n if (deg2.size()==1) return 1;\n for (auto [a, b] : deg2) {\n grid[a][b] = 0;\n memset(deg, -1, sizeof(deg));// Reset\n int cnt=component(grid);\n if (cnt!=1) return 1;\n grid[a][b] = 1;\n }\n\n return 2;\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n``` | 14 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'C++'] | 2 |
minimum-number-of-days-to-disconnect-island | [Java] O(MN) 2ms articulation point/bridge approach | java-omn-2ms-articulation-pointbridge-ap-vzob | All the posted solutions are using the similar basic flow: \n1. If there is no island or more than 1 island, return 0;\n2. If there is only one land, return 1;\ | caohuicn | NORMAL | 2020-08-31T04:57:43.149603+00:00 | 2020-09-01T00:14:58.620663+00:00 | 1,607 | false | All the posted solutions are using the similar basic flow: \n1. If there is no island or more than 1 island, return 0;\n2. If there is only one land, return 1;\n3. If any single cell could serve as the cut point ( divide 1 island into 2 islands), return 1;\n4. Otherwise, return 2 ( I haven\'t found a formal proof yet).\n\nThe major difference is how to find single cut point. Solutions like BFS/DFS/UnionFind all have to try each and every land cell, resulting in **O(M^2N^2)** worst case time complexity. We could use Tarjan\'s algorithm to find the articulation point with **O(MN)** time complexity(https://en.wikipedia.org/wiki/Biconnected_component). It\'s similar to my original bridge solution, except that it\'s shorter and more intuitive.\n\n```\nclass Solution {\n boolean ap; //articulation point\n int time; //visit time\n int[][] dir = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n public int minDays(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n ap = false;\n time = 0;\n int lands = 0, islands = 0;\n int[][] depth = new int[n][m];\n int[][] low = new int[n][m];\n int[][] parent = new int[n][m];\n for (int i = 0; i < n; i++) {\n Arrays.fill(depth[i], -1);\n Arrays.fill(low[i], -1);\n Arrays.fill(parent[i], -1);\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n lands++;\n if (depth[i][j] == -1) {\n apDFS(grid, i, j, depth, low, parent);\n islands++;\n }\n }\n }\n }\n\n if (islands == 0 || islands >= 2) return 0;\n if (lands == 1) return 1;\n if (ap) return 1;\n return 2;\n }\n\n private void apDFS(int[][] grid, int i, int j, int[][] depth, int[][] low, int[][] parent) {\n int n = grid.length, m = grid[0].length;\n depth[i][j] = time++;\n low[i][j] = depth[i][j];\n int children = 0;\n for (int k = 0; k < dir.length; k++) {\n int ni = i + dir[k][0];\n int nj = j + dir[k][1];\n if (ni >= 0 && ni < n && nj >= 0 && nj < m && grid[ni][nj] == 1) {\n //valid connection\n if (depth[ni][nj] == -1) {\n children++;\n parent[ni][nj] = i*m + j;\n apDFS(grid, ni, nj, depth, low, parent);\n low[i][j] = Math.min(low[i][j], low[ni][nj]);\n if (low[ni][nj] >= depth[i][j] && parent[i][j] > -1) {\n ap = true;\n }\n } else if (ni*m + nj != parent[i][j]) {//ignore the incoming path\n low[i][j] = Math.min(low[i][j], depth[ni][nj]);\n }\n }\n }\n if (parent[i][j] == -1 && children > 1) {\n ap = true;\n }\n }\n}\n```\n\n#### Original bridge solution\n<details>\n <summary>Click to expand!</summary>\nHere is a solution using Tarjan\'s algorithm to find the bridge in **O(MN)** time. See [**here**](https://stackoverflow.com/questions/28917290/how-can-i-find-bridges-in-an-undirected-graph) for details. \n\nOne minor difference between our solution and the original algorithm (https://algs4.cs.princeton.edu/41graph/Bridge.java.html) is: we\'re not trying to cut the connection (the boundary between cells with value 1), we\'re trying to cut a cell, which might have 4 connections. So it\'s not done when we find a bridge, we also need to make sure either cell of the bridge has other connections. E.g. in case of `[[1,1]]`, we do have a bridge, but removing either cell of the bridge doesn\'t make it 2 islands.\n\n```\nclass Solution {\n public int minDays(int[][] grid) {\n int c = getIslands(grid);\n if (c == 0 || c >= 2) return 0;\n if (hasOneLand(grid)) return 1;\n if (hasBridge(grid)) return 1;\n return 2;\n }\n\n private boolean hasOneLand(int[][] grid) {\n int n = grid.length, m = grid[0].length, c = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 && ++c > 1) {\n return false;\n }\n }\n }\n return c == 1;\n }\n\n boolean found = false;//whether there\'s a bridge\n int cnt = 0;//node dfs visit sequence number\n private boolean hasBridge(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n found = false;\n cnt = 0;\n int[][] pre = new int[n][m];\n int[][] low = new int[n][m];\n for (int i = 0; i < n; i++) {\n Arrays.fill(pre[i], -1);\n Arrays.fill(low[i], -1);\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 && pre[i][j] == -1) {\n bridgeDFS(grid, i, j, i, j, pre, low);\n if (found) return true;\n }\n }\n }\n return false;\n }\n\n /**\n *\n * @param i1 from row\n * @param j1 from column\n * @param i current row\n * @param j current column\n * @param pre array that keeps track of current cnt during dfs; -1 means not visited\n * @param low lowest pre order that\'s connected to the current node\n */\n private void bridgeDFS(int[][] grid, int i1, int j1, int i, int j, int[][] pre, int[][] low) {\n int n = grid.length, m = grid[0].length;\n pre[i][j] = cnt++;\n low[i][j] = pre[i][j];\n for (int k = 0; k < dir.length; k++) {\n int ni = i + dir[k][0];\n int nj = j + dir[k][1];\n if (ni >= 0 && ni < n && nj >= 0 && nj < m && grid[ni][nj] == 1) {\n //valid connection\n if (pre[ni][nj] == -1) {\n bridgeDFS(grid, i, j, ni, nj, pre, low);\n low[i][j] = Math.min(low[i][j], low[ni][nj]);\n if (low[ni][nj] == pre[ni][nj]) {\n //i,j to ni, nj is bridge. (i,j) or (ni,nj) must have other neighbors for the cell to be the cut point\n if (hasMoreNeighbors(grid, i, j) || hasMoreNeighbors(grid, ni, nj)) {\n //shortcut, no need to search any more\n found = true;\n return;\n }\n }\n } else if (ni != i1 || nj != j1) {//ignore the incoming path\n low[i][j] = Math.min(low[i][j], pre[ni][nj]);\n }\n }\n }\n }\n\n /**\n * Returns whether the cell has 2 or more neighbors\n */\n private boolean hasMoreNeighbors(int[][] grid, int i, int j) {\n int c = 0;\n for (int k = 0; k < dir.length; k++) {\n int ni = i + dir[k][0];\n int nj = j + dir[k][1];\n if (ni >= 0 && ni < grid.length && nj >= 0 && nj < grid[0].length && grid[ni][nj] == 1) {\n c++;\n }\n }\n return c > 1;\n }\n\n /**\n * Gets number of islands\n */\n private int getIslands(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n boolean[][] v = new boolean[n][m];\n int c = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 && !v[i][j]) {\n dfsIslands(grid, i, j, v);\n c++;\n }\n }\n }\n return c;\n }\n\n int[][] dir = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n private void dfsIslands(int[][] grid, int i, int j, boolean[][] v) {\n if (v[i][j]) return;\n v[i][j] = true;\n for (int k = 0; k < dir.length; k++) {\n int ni = i + dir[k][0];\n int nj = j + dir[k][1];\n if (ni >= 0 && ni < grid.length && nj >= 0 && nj < grid[0].length && grid[ni][nj] == 1) {\n dfsIslands(grid, ni, nj, v);\n }\n }\n }\n\n}\n```\n \n </details>\n | 13 | 0 | [] | 2 |
minimum-number-of-days-to-disconnect-island | [Python] O(N*M) | Articulation Points | Beats 100% | python-onm-articulation-points-beats-100-4lbt | This question can be divided into 3 cases :\n\n1) The most number of cells to be removed in the worst case will be 2, explained later.\n2) If there is an articu | zypher27 | NORMAL | 2020-08-30T17:17:11.817957+00:00 | 2020-09-16T12:47:48.612007+00:00 | 1,269 | false | This question can be divided into 3 cases :\n\n1) The most number of cells to be removed in the worst case will be 2, explained later.\n2) If there is an articulation point, the answer will be 1.\n3) The matrix is already divided or there are no 1\'s, the answer is 0.\n\n\nSo, if you didnt understand the worst case scenario, \nhere is an example:\n```\n1 1 1 1 1 1\n1 1 1 1 1 1\n1 1 1 1 1 1\n1 1 1 1 1 1\n\nwe just change two 1\'s\n\n1 0 1 1 1 1\n0 1 1 1 1 1\n1 1 1 1 1 1\n1 1 1 1 1 1\n```\nSo, the answer will be always 2 at max.\n\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n cnt = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]:\n cnt += 1 # count the number of elements\n root = (i, j) # assign the root node for the graph\n \n if cnt <= 1 : return cnt # no elements in the map\n \n vis, low, time, res = {root}, {}, {}, []\n \n # find whether articulation points are present in the matrix\n def articulation_points(curr, parent): \n low[curr] = time[curr] = len(vis)\n children = 0\n i, j = curr\n \n for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n if (x, y) == parent : continue\n \n if 0<=x<len(grid) and 0<=y<len(grid[0]) and grid[x][y]:\n if (x, y) not in vis:\n vis.add((x,y))\n articulation_points((x,y), curr)\n low[curr] = min(low[curr], low[(x, y)])\n children += 1\n if low[(x, y)] >= time[(curr)] and parent!=(-1, -1):\n res.append([i, j])\n else:\n low[curr] = min(low[curr], time[(x, y)])\n \n if parent == (-1, -1) and children > 1:\n res.append([x, y])\n\n articulation_points(root, (-1, -1))\n\n if len(vis) != cnt: # if the matrix is disconnected beforehand\n return 0\n elif res: # if there are any articulation points\n return 1\n else: # worst case, no articulation points\n return 2\n \n```\n\nTime = Space = O(N* M) | 12 | 0 | ['Python'] | 5 |
minimum-number-of-days-to-disconnect-island | C++ easy to understand with explanation BFS | c-easy-to-understand-with-explanation-bf-qih4 | Looking at the question, it might give an impression as a very difficult question. This question actually is lot easier than it looks. On careful observation, y | mohithakhil | NORMAL | 2020-08-30T05:39:31.947800+00:00 | 2020-08-30T05:42:41.348303+00:00 | 1,115 | false | Looking at the question, it might give an impression as a very difficult question. This question actually is lot easier than it looks. On careful observation, you can notice that the answer can only lie between 0 and 2. \n\nWhen does answer can be 0? If the given matrix already contains more than one island or if the matrix doesn\'t contain any island. When can the answer be 1 or 2 and why can\'t it be greater than 2?\n\nNotice that the question just wants you to disconnect the grid. It doesn\'t matter how many elements are present in the islands that are formed after disconnecting the original grid. We can disconnect the corners from the island and can achieve a disconnected grid. Disconnecting corners from the original grid require at max 2 operations. Consider the following examples:\n```\n0 1 1 0\n0 1 1 0\n0 0 0 0\n```\nDisconecting the corner (0,1) in the above example requires two operations. grid[0][2]=0 and grid[1][1]=0. Sometimes it requires just one operation like in the following case:\n```\n0 1 1 0\n0 0 1 0\n0 0 0 0\n```\nNote that I am talking about corners of the grid. Corners are connected to a grid in atmax two directions only out of 4 possible directions. But what about the following cases \n\n```\n0 1 1 1 0 1 1 1 1 1\n 1 1 1 0 1\n```\nAbove two examples require just one move and that move in both the cases is not a corner. \nWhat we can do is change one 1 in the entire grid to 0 and check if two islands are formed. If formed, then the answer is 1. If two islands can\'t be formed by changing just one 1 to 0, then answer is 2. Consider the following algorithm for clear understanding.\n\n```\n1. Check if given grid contains 0 or more than 1 island using bfs. If yes, return 0.\n2. For each element having value 1 present in the grid, change it to 0 and apply bfs. If more than two islands are formed, then the answer is 1.\n3. If there is no way we can change just one element to 0 and get a disconnected grid, then the answer is 2.\n````\n\nCheck the following code for clearer understanding:\n\n```\nclass Solution {\npublic:\n int bfs(vector<vector<int>>&grid)\n {\n int num_islands=0;\n int m=grid.size();\n int n=grid[0].size();\n unordered_set<int>set;\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(grid[i][j]==0 || set.find(i*n+j)!=set.end())\n continue;\n num_islands++;\n if(num_islands>1)\n return 2;\n queue<int>q;\n q.push(i*n+j);\n set.insert(i*n+j);\n while(!q.empty())\n {\n int temp=q.front();\n q.pop();\n int x=temp/n;\n int y=temp%n;\n if(x<m-1 && grid[x+1][y]==1 && set.find((x+1)*n+y)==set.end())\n {\n set.insert((x+1)*n+y);\n q.push((x+1)*n+y);\n }\n if(x>0 && grid[x-1][y]==1 && set.find((x-1)*n+y)==set.end())\n {\n set.insert((x-1)*n+y);\n q.push((x-1)*n+y);\n }\n if(y<n-1 && grid[x][y+1]==1 && set.find(x*n+y+1)==set.end())\n {\n set.insert(x*n+y+1);\n q.push(x*n+y+1);\n }\n if(y>0 && grid[x][y-1]==1 && set.find(x*n+y-1)==set.end())\n {\n set.insert(x*n+y-1);\n q.push(x*n+y-1);\n }\n }\n }\n }\n return num_islands;\n }\n int minDays(vector<vector<int>>& grid) \n {\n if(bfs(grid)!=1)\n return 0;\n \n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n if(grid[i][j]==0)\n continue;\n grid[i][j]=0;\n if(bfs(grid)!=1)\n return 1;\n grid[i][j]=1;\n }\n }\n return 2;\n \n }\n};\n\n```\n\nComplexity analysis:\nSince we are performing bfs repeatedly, time complexity of O(m^2 * n^2)\n```\nTime complexity: O(m^2 * n^2)\nSpace complexity: O(m*n)\n```\n\nUpvote if you found the solution useful. If you found any difficulty in understanding the explanation or the code, or if you want to suggest any improvements, please comment. | 12 | 3 | ['Breadth-First Search', 'C'] | 3 |
minimum-number-of-days-to-disconnect-island | Beginner Friendly Solution with Brute Force DFS + Visualization + Step Explanation 😊😊 | beginner-friendly-solution-with-brute-fo-zs7h | Intuition\nThe problem asks us to find the minimum number of days required to disconnect a single island in a grid. The intuition is to:\n\n1. Identify if there | briancode99 | NORMAL | 2024-08-10T18:25:43.406718+00:00 | 2024-08-10T18:25:43.406748+00:00 | 1,285 | false | # Intuition\nThe problem asks us to find the minimum number of days required to disconnect a single island in a grid. The intuition is to:\n\n1. Identify if there are multiple islands: If there are multiple islands, it\'s already disconnected, and we need 0 days.\n2. Disconnect the single island: We need to find a way to turn land cells (1) into water cells (0) to break the connection between land cells, effectively disconnecting the island.\n3. Check for successful disconnection: After changing a land cell to water, we need to re-evaluate the number of islands to see if it\'s now disconnected. (brute force)\n\n# Approach\n1. Count Islands: Implement a function countIslands that uses depth-first search (DFS) to traverse and count the number of islands in the grid.\n2. Initial Island Count: Call countIslands to get the initial number of islands. If it\'s not 1, return 0 as the island is already disconnected.\n3. One-Day Disconnection: Loop through each cell in the grid. For each land cell (1):\n - Change the land cell to water (0).\n - Re-count the islands using countIslands. (brute force)\n - If the number of islands is no longer 1, return 1 as the island is disconnected in one day.\n - Revert the land cell back to its original state (1).\n4. Two-Day Disconnection: If no single cell change disconnects the island, it means the island is a single connected block. Therefore, we need two days to disconnect it by changing two adjacent land cells to water. Return 2.\n\n# Complexity\n- Time complexity: O(m^2 * n^2)\n\n- Space complexity: O(m * n)\n\n# Visualization and Step Explanation\nFirst of all I want to say that this solution is brute force, so the solution is not optimized to beat other optimized solution. But since this question is already hard, the brute force solution is the most intuitive solution that we can come up with and possibly lead to other optimized, so nevertheless the brute force solution is still important to understand.\n\n- Count Initial Islands:\n\n - This can be easily achieve with dfs to search for the number of islands. \n - The code is also similar with the "Number of Island" problem.\n - Here my solution for "Number of Islands" problem if you needed. (https://leetcode.com/problems/number-of-islands/solutions/5616162/beginner-friendly-solution-with-matrix-and-depth-first-search-dfs/)\n - Visual Example:\n - \n - Initially there is ONE island in this grid.\n\n- Check the number of island:\n - If the number of island is not one meaning either we have no island at all or the number of island already disconnected then we just return 0, since the island already disconnected\n - If the number of island is EXACTLY ONE then we need to do some disconnection, but here is the most important part. The number of disconnection that can happen is either 1 or 2 as explain greatly by this discussion (https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/description/comments/2129267).\n\n- Island Count is One:\n - Try to disconnect the island by switching land (1) to water (0) everytime we find land (1).\n - Then brute forcelly check for the number of island again, if the number of island is still one then we not yet disconnect the island so we need to keep doing it. But if the number of island not equal to one then we disconnected it so we can return 1.\n - Keep doing it until the end of the grid if we cannot disconnected in one day then return 2.\n - Visual Example:\n - \n - Since the initial number of island is ONE we need to do the switching of island. The first time we encounter a land we flip it to water and we got the number of island as ONE again.\n - \n - The second time we encounter a land we flip it to water and we got the number of island as ONE again.\n - \n - The third time we encounter a land we flip it to water and we got the number of island as ONE again.\n - \n - The fourth and last time we encounter a land we flip it to water and we got the number of island as ONE again.\n - Since we don\'t encounter any land anymore we can return 2 as our answer.\n\nThat\'s all, thank you and good luck. I also try to put a lot of comment in the code for reference, I hope you like it. \uD83D\uDE0A\uD83D\uDE0A\n\n# Code\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst directions = [\n [-1, 0], // up\n [0, 1], // right\n [1, 0], // down\n [0, -1], //left\n];\n\nvar minDays = function (grid) {\n // count islands\n const islandCount = countIslands(grid);\n\n // 0 case: no islands or more than one island\n if (islandCount !== 1) {\n return 0;\n }\n\n // 1 case: can disconnect island in one day (islandCount === 1)\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[0].length; col++) {\n // only try to disconnect when the grid is land (1) not water (0)\n if (grid[row][col] === 1) {\n // change island to water\n grid[row][col] = 0;\n\n // brute forcelly get new island count and check for the number of island like the zero case\n const newIslandCount = countIslands(grid);\n\n // check if disconnected\n if (newIslandCount !== 1) {\n return 1;\n }\n\n // if doesn\'t work then revert back to land (1)\n grid[row][col] = 1;\n }\n }\n }\n\n // 2 case: cannot disconnect island in one day (islandCount === 1)\n return 2;\n};\n\n// helper function to count number of islands\nfunction countIslands(grid) {\n let count = 0;\n\n // get row length and col length\n const rowLength = grid.length;\n const colLength = grid[0].length;\n // intialize visited matrix by filling all to false\n const visited = new Array(grid.length)\n .fill(null)\n .map(() => new Array(grid[0].length).fill(false));\n\n // do sequential search from [0,0]\n for (let row = 0; row < rowLength; row++) {\n for (let col = 0; col < colLength; col++) {\n // found new island\n if (grid[row][col] === 1 && !visited[row][col]) {\n exploreIslandDFS(grid, row, col, visited);\n count++;\n }\n }\n }\n\n return count;\n}\n\n// helper function to explore island using dfs (this code really similar to "Number of Islands" problem)\nfunction exploreIslandDFS(grid, row, col, visited) {\n visited[row][col] = true;\n\n // check neighboring value of 4-directions\n for (let direction of directions) {\n const nextRow = row + direction[0];\n const nextCol = col + direction[1];\n\n // keep doing dfs if it valid (still in range of the matrix, not yet visited and the neighboring value is 1)\n if (\n nextRow >= 0 &&\n nextRow < grid.length &&\n nextCol >= 0 &&\n nextCol < grid[0].length &&\n !visited[nextRow][nextCol] &&\n grid[nextRow][nextCol] === 1\n ) {\n exploreIslandDFS(grid, nextRow, nextCol, visited);\n }\n }\n}\n``` | 10 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'JavaScript'] | 3 |
minimum-number-of-days-to-disconnect-island | Articulation point | articulation-point-by-shivam565-6dus | there are only 3 possible cases:\n\n if the graph already has more than 1 components\n if the graph has atleast one articulation point\n if the graph does\'t fo | shivam565 | NORMAL | 2022-08-28T09:56:30.718507+00:00 | 2022-08-28T09:59:05.068957+00:00 | 915 | false | there are only 3 possible cases:\n\n* **if the graph already has more than 1 components**\n* **if the graph has atleast one articulation point**\n* **if the graph does\'t follow those two rules**\n\n\n<br>\n<br>\n<br>\nin the first case the ans is 0 becuse we don\'t need to convert any 1 to 0 because graph is already disconnected<br>\nin the second case the ans is 1 because by removing that point graph will be divided into two components<br>\nin the third case we will make any of the boundry 1 as a seperate componet.<br>\n\n**e.g.**<br>\nin this case the ans is 1 because if we remove any of those nodes graph is divided into two components.<br>\n\n\n\nin that case if we make the boundry 1 as seprate component by removing red cells the graph is disconnected,because either the rest two cells are not valid or it has water in those cells.\n\n\n\n\n**Code:**\n```\nclass Solution {\npublic:\n int minDays(vector<vector<int>>& grid) {\n //if the graph has already greater than 1 components than ans is 0\n //if the graph has any articulation point than ans is 1\n //else ans is 2\n int n = grid.size();\n int m = grid[0].size();\n int count = 0;\n //discovery time\n vector<vector<int>> disc(n,vector<int>(m,0));\n //low time\n vector<vector<int>> low(n,vector<int>(m,0));\n //visited array\n vector<vector<bool>> visited(n,vector<bool>(m,false));\n //direction array\n int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};\n //if ok is true means there is a articulation point in the graph\n bool ok = false;\n //dfs call\n function<void(int,int,int&,int)> dfs = [&](int x,int y,int &time,int p){\n //mark the nodes as visited and update their low and disc time\n visited[x][y] = true;\n disc[x][y] = low[x][y] = time++;\n //for root if there are more than 1 recursive tree than root is a articulation point\n int rootCall = 0;\n //going in all direction and making a dfs call\n for(int i = 0 ; i < 4 ; i++){\n int newX = x+dir[i][0];\n int newY = y+dir[i][1];\n //if child cordinates are valid and there is a 1 at that point ans also it is not parent\n if(newX >= 0 && newX < n && newY >= 0 && newY < m && grid[newX][newY] == 1 && newX*m+newY != p){\n if(!visited[newX][newY]){\n dfs(newX,newY,time,x*m+y);\n //update the low time\n low[x][y] = min(low[x][y],low[newX][newY]);\n //checking whether [x,y] is articulation point or not\n if(p == -1){\n rootCall++;\n }else if(disc[x][y] <= low[newX][newY]){\n ok = true;\n }\n }else{\n //updating the low time\n low[x][y] = min(low[x][y],disc[newX][newY]);\n }\n }\n }\n //if root and more than 1 recurive tree formed than articulation point\n if(p == -1 && rootCall > 1){\n ok = true;\n }\n };\n //counting the number of 1\'s and making dfs call\n int to1 = 0;\n for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n if(grid[i][j] == 1){\n to1++;\n if(!visited[i][j]){\n int time = 1;\n dfs(i,j,time,-1);\n count++;\n }\n }\n }\n }\n \n if(count > 1){\n //if more than one components are formed\n return 0;\n }else if(ok){\n //if onlu one component is formed and there is a articulation point\n return 1;\n }else{\n //if total number of 1 is 1\n if(to1 == 1){\n return 1;\n }else if(to1 == 0){\n //if total number of 1 is 0\n return 0;\n }\n //else\n return 2;\n }\n }\n};\n```\n\n | 10 | 0 | ['C'] | 1 |
minimum-number-of-days-to-disconnect-island | Simplest explanation (with diagram). Articulation Point - Tarjan Algo. Faster than 100% | simplest-explanation-with-diagram-articu-psfz | Now, first of all how many solutions can be there, I will say only 0,1 and 2, why ?\n\n### 1. for \'0\'\na. there is a initially more than one connected compone | himanshuaswal | NORMAL | 2021-06-24T10:08:23.965994+00:00 | 2021-06-24T10:08:23.966041+00:00 | 2,202 | false | # Now, first of all how many solutions can be there, I will say only 0,1 and 2, **why** ?\n\n### 1. for \'0\'\na. there is a initially more than one connected components.\nwhich is quite easy to find, just using a dfs/bfs.\nb. there is no land (all zeroes in grid).\n\n### 2. for \'2\'\n\n at max you can remove 2 connecting node of any **corner node**(as there always be a corner) to make it disconnected.\n\n\n### 3. for \'1\' (most important case)\na. if there is only one node of land, i.e. only one \'1\' in the grid.\n#### b. if there is any articulation point present in the grid.\nArticulation point is a point in a graph, which on removing increases the number of connected conponents of that graph.\nex. **(articulation point marked in red)**\n1. \n2. \n\nSo what I did is first find that if there is only:\n1. one \'1\': return 1;\n2. all \'0\': return 0;\n3. all \'1\': return 2;\n\nThen applied simple tarjan algo to find articulation point(explaining it here is just useless as there are some very nice videos out there on youtube) to find if there is any articuation point or not. And as tarjan algo is just a dfs traversal, it will traverse all the nodes in **one connected component".** So, if there is any node which is \'1\' and not visited yet, then that means that there is more than one connected component (just return 0;). after that if there is any articulation point in the graph, return 1. Otherwise return 2.\n\nCode:\n```\nclass Solution {\npublic:\n int t = 0;\n bool isArticulation = 0;\n vector<pair<int, int>>moves = {{ -1, 0}, {0, -1}, {0, 1}, {1, 0}};\n bool check(int r, int c, int n, int m) {\n return (r<n and r >= 0 and c<m and c >= 0);\n }\n\n void tarjan(int r, int c, vector<vector<int>>&a, vector<vector<int>>&visit_time, vector<vector<int>>&low_time, vector<vector<pair<int, int>>>&parent, int parR, int parC, int n, int m) {\n visit_time[r][c] = low_time[r][c] = t;\n parent[r][c] = {parR, parC};\n t += 1;\n int child = 0;\n for (auto x : moves) {\n if (check(r + x.first, c + x.second, n, m) and a[r + x.first][c + x.second] == 1) {\n if (visit_time[r + x.first][c + x.second] == -1) {\n child += 1;\n tarjan(r + x.first, c + x.second, a, visit_time, low_time, parent, r, c, n, m);\n low_time[r][c] = min(low_time[r][c], low_time[r + x.first][c + x.second]);\n\n if (child > 1 and parent[r][c].first == -1) {\n isArticulation = 1;\n // return;\n }\n\n if (low_time[r + x.first][c + x.second] >= visit_time[r][c] and parent[r][c].first != -1) {\n isArticulation = 1;\n // return;\n }\n }\n else if (r + x.first != parent[r][c].first or c + x.second != parent[r][c].second) {\n low_time[r][c] = min(low_time[r][c], low_time[r + x.first][c + x.second]);\n }\n }\n }\n }\n\n int minDays(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n\n int zeroSum = 0, oneSum = 0;\n for (auto x : grid) {\n for (auto y : x) {\n if (y == 0) zeroSum += 1;\n if (y == 1) oneSum += 1;\n }\n }\n if (oneSum == 1) {\n return 1;\n }\n\n if (zeroSum == n * m) {\n return 0;\n }\n if (oneSum == n * m) {\n return 2;\n }\n vector<vector<int>>visit_time(n, vector<int>(m, -1));\n vector<vector<int>>low_time(n, vector<int>(m, INT_MAX));\n vector<vector<pair<int, int>>>parent(n, vector<pair<int, int>>(m));\n bool tarjanDone = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 and visit_time[i][j] == -1 and !tarjanDone) {\n tarjan(i, j, grid, visit_time, low_time, parent, -1, -1, n, m);\n tarjanDone = 1;\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 and visit_time[i][j] == -1) {\n return 0;\n }\n }\n }\n\n if (isArticulation) {\n return 1;\n }\n return 2;\n // return 0;\n }\n};\n```\n | 9 | 0 | ['Depth-First Search', 'Graph'] | 5 |
minimum-number-of-days-to-disconnect-island | Java Clean - Tarjan O(mn) | java-clean-tarjan-omn-by-rexue70-4v1g | This question is similar to question 1192 https://leetcode.com/problems/critical-connections-in-a-network/description/\nwe use tarjan\'s algorithm to record (ev | rexue70 | NORMAL | 2020-09-01T05:37:42.296311+00:00 | 2020-09-01T09:27:25.746975+00:00 | 1,117 | false | This question is similar to question 1192 https://leetcode.com/problems/critical-connections-in-a-network/description/\nwe use tarjan\'s algorithm to record (every node) id and the (lowest id it can reach), if we find a critical edge, which means we can cut the island two parts by one cut.\n```\nclass Solution {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n Map<Integer, Integer> timeMap = new HashMap<>();\n boolean foundCriticalEdge;\n int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n int root = -1, time = 0, count = 0;\n\n public int minDays(int[][] grid) {\n if (noOfIsland(grid) != 1) return 0;\n if (count == 2) return 2;\n buildGraph(grid); //build graph\n tarjan(-1, root, 0, new HashSet<>()); //(parent, cur, id_time, visietd)\n return foundCriticalEdge ? 1 : 2;\n }\n \n private void tarjan(int parent, int cur, int time, Set<Integer> visited) {\n visited.add(cur);\n timeMap.put(cur, time);\n for (int nei : graph.get(cur)) {\n if (nei == parent) continue;\n if (!visited.contains(nei)) tarjan(cur, nei, time + 1, visited);\n if (time < timeMap.get(nei)) foundCriticalEdge = true;\n timeMap.put(cur, Math.min(timeMap.get(cur), timeMap.get(nei))); \n }\n }\n \n public void buildGraph(int[][] grid) {\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == 1)\n for (int[] dir : dirs)\n mark(grid, i, j, i + dir[0], j + dir[1]);\n }\n \n public void mark(int grid[][], int prevX, int prevY, int x, int y) {\n if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0) return;\n int n1 = prevX * grid[0].length + prevY;\n int n2 = x * grid[0].length + y;\n graph.computeIfAbsent(n1, value -> new ArrayList<>()).add(n2);\n graph.computeIfAbsent(n2, value -> new ArrayList<>()).add(n1);\n }\n \n private int noOfIsland(int[][] grid) {\n int res = 0;\n boolean[][] visited = new boolean[grid.length][grid[0].length];\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (!visited[i][j] && grid[i][j] == 1) {\n if (root == -1) root = i * grid[0].length + j;\n res++;\n dfs(visited, grid,i,j);\n }\n return res;\n }\n \n private void dfs(boolean[][] visited, int[][] grid, int i, int j) {\n if (i < 0 || j < 0 || i == grid.length || j == grid[0].length || visited[i][j] || grid[i][j] == 0) return;\n count++;\n visited[i][j] = true;\n for (int[] dir : dirs) \n dfs(visited, grid, i + dir[0], j + dir[1]);\n }\n}\n```\n\n\n\n\nOr if you prefer the text book version, which is directly transfered from pseudo code\n```\nclass Solution {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n boolean foundCriticalEdge;\n int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n int root = -1, time = 0, count = 0;\n int[] dfn; int[] low;\n \n public int minDays(int[][] grid) {\n if (noOfIsland(grid) != 1) return 0;\n if (count == 2) return 2;\n buildGraph(grid); //build graph\n int m = grid.length, n = grid[0].length;\n dfn = new int[m * n]; low = new int[m * n]; //Trajan\'s algorithm\n Arrays.fill(dfn, -1);\n tarjan(-1, root); //(parent, cur, id_time, visietd)\n return foundCriticalEdge ? 1 : 2;\n }\n \n private void tarjan(int prev, int cur) {\n if (foundCriticalEdge) return;\n dfn[cur] = low[cur] = ++time;\n for (int nei : graph.get(cur)) {\n if (nei == prev) continue;\n if (dfn[nei] == -1) {\n tarjan(cur, nei);\n if (low[nei] > dfn[cur]) {\n foundCriticalEdge = true;\n // return;\n }\n }\n low[cur]=Math.min(low[cur],low[nei]);\n }\n }\n \n\n public void buildGraph(int[][] grid) {\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (grid[i][j] == 1)\n for (int[] dir : dirs)\n mark(grid, i, j, i + dir[0], j + dir[1]);\n }\n \n public void mark(int grid[][], int prevX, int prevY, int x, int y) {\n if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0) return;\n int n1 = prevX * grid[0].length + prevY;\n int n2 = x * grid[0].length + y;\n graph.computeIfAbsent(n1, value -> new ArrayList<>()).add(n2);\n graph.computeIfAbsent(n2, value -> new ArrayList<>()).add(n1);\n }\n \n private int noOfIsland(int[][] grid) {\n int res = 0;\n boolean[][] visited = new boolean[grid.length][grid[0].length];\n for (int i = 0; i < grid.length; i++)\n for (int j = 0; j < grid[0].length; j++)\n if (!visited[i][j] && grid[i][j] == 1) {\n if (root == -1) root = i * grid[0].length + j;\n res++;\n dfs(visited, grid,i,j);\n }\n return res;\n }\n \n private void dfs(boolean[][] visited, int[][] grid, int i, int j) {\n if (i < 0 || j < 0 || i == grid.length || j == grid[0].length || visited[i][j] || grid[i][j] == 0) return;\n count++;\n visited[i][j] = true;\n for (int[] dir : dirs) \n dfs(visited, grid, i + dir[0], j + dir[1]);\n }\n}\n``` | 9 | 1 | [] | 5 |
minimum-number-of-days-to-disconnect-island | Python easy | python-easy-by-valkyre_queen-a5v3 | The answer can be atmost 2 as \n--->For example number of islands are not 1 we can return 0 as there is no need to do anything\n--->If there is 1 island we can | valkyre_queen | NORMAL | 2020-08-30T08:51:32.936553+00:00 | 2020-09-02T03:49:39.690240+00:00 | 648 | false | The answer can be atmost 2 as \n--->For example number of islands are not 1 we can return 0 as there is no need to do anything\n--->If there is 1 island we can return 1 as 1 step will be sufficient to break them into\n--->If there is 1 island and we cannot break them into 2 islands in 1 day we are left with only one option which 2 so return 2\n\nActually this question can be divided into 2 parts one is [Count islands](https://leetcode.com/problems/number-of-islands/) and next part is as mentioned above\n\n\n\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n \n def countislands(grid):\n islands = 0\n visited = set()\n\n def dfs(grid,row,col,visited):\n if 0 <= row < len(grid) and 0 <= col < len(grid[0]) and grid[row][col] == 1 and (row,col) not in visited:\n visited.add((row,col))\n dfs(grid,row+1,col,visited)\n dfs(grid,row-1,col,visited)\n dfs(grid,row,col+1,visited)\n dfs(grid,row,col-1,visited)\n\n\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == 1 and (row,col) not in visited:\n islands += 1\n dfs(grid,row,col,visited)\n \n return islands\n \n if countislands(grid) != 1:\n return 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]:\n grid[i][j] = 0\n if countislands(grid) != 1:\n return 1\n grid[i][j] = 1\n return 2\n\t\t\n\t | 9 | 2 | ['Depth-First Search', 'Python'] | 1 |
minimum-number-of-days-to-disconnect-island | [Java] Remove at most two | java-remove-at-most-two-by-ycj28c-wk7t | The trick is maximum remove 2 points can get more than two islands.... - -\nThere is always one node in the cornor, for example:\n0 1 1 1 0\n0 1 1 1 0\n0 1 1 1 | ycj28c | NORMAL | 2020-08-30T04:28:26.288121+00:00 | 2020-08-30T06:13:14.474362+00:00 | 1,086 | false | The trick is maximum remove 2 points can get more than two islands.... - -\nThere is always one node in the cornor, for example:\n0 1 1 1 0\n0 1 1 1 0\n0 1 1 ***1*** 0\n0 0 0 0 0\nwe can always remove the point next to the right-bottom 1 to get more than 2 island, this case we remove [1,3],[2,2]\n0 1 1 1 0\n0 1 1 0 0\n0 1 0 ***1*** 0\n0 0 0 0 0\nSo only need remove at most 2\n\nspecial case, \n0 1s, then return 0;\n1 1s, then return 1;\n\nJust need to verify the remove 1 point case... \n```\nclass Solution {\n public int minDays(int[][] grid) {\n Set<Integer> ones = new HashSet<>();\n \n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[0].length;j++){\n if(grid[i][j] == 1){\n ones.add(i * grid[0].length + j);\n }\n }\n }\n if(ones.size() == 0) return 0;\n if(ones.size() == 1) return 1;\n if(moreThanOneIsland(grid, ones)) return 0;\n \n Set<Integer> tmp = new HashSet<>(ones);\n for(int one : ones){\n tmp.remove(one);\n if(moreThanOneIsland(grid, tmp)) return 1;\n tmp.add(one);\n }\n return 2;\n }\n private int[][] dirs = new int[][]{{-1,0},{1,0},{0,1},{0,-1}};\n //if can\'t access all island, means more than 2 island, O(K)\n private boolean moreThanOneIsland(int[][] grid, Set<Integer> ones){\n Queue<Integer> queue = new LinkedList<>();\n int start = ones.iterator().next();\n queue.offer(start);\n Set<Integer> visited = new HashSet<>();\n visited.add(start);\n while(!queue.isEmpty()){\n int point = queue.poll();\n visited.add(start);\n int x = point / grid[0].length;\n int y = point % grid[0].length;\n for(int[] dir : dirs){\n int newX = x + dir[0];\n int newY = y + dir[1];\n if(newX >=0 && newX < grid.length && newY >=0 && newY < grid[0].length){\n int key = newX * grid[0].length + newY;\n if(!visited.contains(key) && ones.contains(key)){\n visited.add(key);\n queue.offer(key);\n }\n }\n }\n }\n return visited.size() < ones.size();\n }\n}\n```\nTime complexity O(MN + K^2), K is the number of ones\nSpace O(K) | 8 | 0 | [] | 2 |
minimum-number-of-days-to-disconnect-island | Easy to understand | Beginner Friendly C++ solution beats 73% | easy-to-understand-beginner-friendly-c-s-b3wr | Intuition\nThe key intuition here is to recognize that we need to find a land cell that, when removed, increases the number of islands. We can achieve this by u | _adarsh_01 | NORMAL | 2024-08-11T06:22:38.825697+00:00 | 2024-08-11T06:22:38.825732+00:00 | 84 | false | # Intuition\nThe key intuition here is to recognize that we need to find a land cell that, when removed, increases the number of islands. We can achieve this by using a depth-first search (DFS) to count the number of islands before and after removing each land cell.\n\nBy iterating through each land cell and checking if its removal increases the number of islands, we can find the minimum number of days required to disconnect the island.\n\n\n# Approach\n\n## This solution uses a two-step approach:\n\n### 1. Island Counting: \n First, we count the number of islands in the original grid using Depth-First Search (DFS). This step helps us understand the initial connectivity of the land cells.\n\n### 2. Removal Simulation: \n Next, we iterate through each land cell and simulate its removal by setting it to 0 (water). We then recount the number of islands using DFS on the modified grid. If the removal results in more than one island, we return 1, indicating that one removal is sufficient to disconnect the island. If no such cell is found, we return 2, implying that two removals are needed.\n\nWe can disconnect the grid within atmost 2 days.\n#### Example\na=[[1,1,1]\n [1,1,1]\n [1,1,1]]\n\nAs connections are only vertical and horizontal.\nLet us think of changing index a[0][1] to 0 then we have \na=[[1,0,1]\n [1,1,1]\n [1,1,1]]\nBut still we have a single component. Now again operation at a[1][0], then we have\na=[[1,0,1]\n [0,1,1]\n [1,1,1]]\nNow we can clearly observe that it has 2 component.\n\n\n# Complexity\n- ### Time complexity:\n O(n*m) for DFS and grid copying\n\n\n- ### Space complexity:\n O(n*m) for grid copying\n\n\n\n# Code\n```\nclass Solution {\n void dfs(vector<vector<int>>&grid,int row,int col){\n int n=grid.size();\n int m=grid[0].size();\n if(row<0 or col<0 or row>=n or col>=m or grid[row][col]==0)return;\n grid[row][col]=0;\n\n int dr[]={1,0,-1,0};\n int dc[]={0,1,0,-1};\n for(int i=0;i<4;i++){\n int nrow=row+dr[i];\n int ncol=col+dc[i];\n dfs(grid,nrow,ncol);\n }\n }\n int number_of_islands(vector<vector<int>>& grid){\n int n=grid.size();\n int m=grid[0].size();\n if(n==0 or m==0)return 0;\n vector<vector<int>>grid_copy=grid;\n int curr=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid_copy[i][j]==1){\n dfs(grid_copy,i,j);\n curr++;\n }\n }\n }\n return curr;\n }\npublic:\n int minDays(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n if(n==0 or m==0)return 0;\n int curr=number_of_islands(grid);\n if(curr!=1){\n return 0;\n }\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1){\n grid[i][j]=0;\n if(number_of_islands(grid)!=1){\n return 1;\n }\n grid[i][j]=1;\n }\n }\n }\n return 2;\n }\n};\n``` | 7 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy Java Solution 🚀 Clean Code . . . | easy-java-solution-clean-code-by-niketh_-hfj9 | Java Code\n---\n> #### Please don\'t forget to upvote if you\'ve liked my solution. \u2B06\uFE0F\n---\n\nclass Solution {\n int[] xDir = {0,0,-1,1};\n int | niketh_1234 | NORMAL | 2023-06-14T17:06:14.774840+00:00 | 2023-06-14T17:06:14.774863+00:00 | 710 | false | # Java Code\n---\n> #### *Please don\'t forget to upvote if you\'ve liked my solution.* \u2B06\uFE0F\n---\n```\nclass Solution {\n int[] xDir = {0,0,-1,1};\n int[] yDir = {-1,1,0,0};\n public boolean isSafe(int[][] grid,int i,int j,boolean[][] visited)\n {\n return(i>=0 && j>=0 && i<grid.length && j<grid[0].length && visited[i][j] == false && grid[i][j] == 1);\n }\n public void islandCount(int[][] grid,int i,int j,boolean[][] visited)\n {\n visited[i][j] = true;\n for(int k = 0;k<4;k++)\n {\n int newRow = i+xDir[k];\n int newCol = j+yDir[k];\n if(isSafe(grid,newRow,newCol,visited))\n {\n islandCount(grid,newRow,newCol,visited);\n }\n }\n }\n public int CountLand(int[][] grid,boolean[][] visited)\n {\n int count = 0;\n for(int i = 0;i<grid.length;i++)\n {\n for(int j = 0;j<grid[0].length;j++)\n {\n if(grid[i][j] == 1 && visited[i][j] == false)\n {\n islandCount(grid,i,j,visited);\n count++;\n }\n }\n }\n return count;\n }\n public int minDays(int[][] grid) {\n int rows = grid.length;\n int cols = grid[0].length;\n boolean[][] visited = new boolean[rows][cols];\n int count = CountLand(grid,visited);\n if(count > 1 || count == 0) return 0;\n for(int i = 0;i<rows;i++)\n {\n for(int j = 0;j<cols;j++)\n {\n if(grid[i][j] == 1)\n {\n grid[i][j] = 0;\n boolean[][] mat = new boolean[rows][cols];\n int count2 = CountLand(grid,mat);\n grid[i][j] = 1;\n if(count2 > 1 || count2 == 0)\n {\n return 1; \n }\n }\n }\n }\n return 2;\n }\n}\n```\n---\n | 7 | 1 | ['Depth-First Search', 'Recursion', 'C++', 'Java', 'Python3'] | 2 |
minimum-number-of-days-to-disconnect-island | [Java] Tarjan 4ms with explain | java-tarjan-4ms-with-explain-by-66brothe-u6jy | Explanation\n1. First let\'s construc a graph\n2. You want to make at least 2 component (if already more than one, just return 0 by doing a simple DFS/BFS check | 66brother | NORMAL | 2020-08-30T06:28:03.224314+00:00 | 2020-09-03T13:54:08.497753+00:00 | 870 | false | **Explanation**\n1. First let\'s construc a graph\n2. You want to make at least 2 component (if already more than one, just return 0 by doing a simple DFS/BFS check)\n3. You want to find a cut point (use tarjan algorithm),the cutpoint is the point where it can split the graph if you remove it and all its adjeccent edges\n4. What about the graph is a strong component(without cut point)? We can think it as a cycle (circle), which means we need to remove at least 2 points to cut the cycle (circle)\n\n```\nclass Solution {\n int cnt=0;\n boolean visit[][];\n int graph[][];\n List<Integer>adjecent[];\n int dis[],low[];\n int time=1;\n boolean cut=false;int root=-1;\n public int minDays(int[][] grid) {\n \n int r=grid.length,c=grid[0].length;\n adjecent=new ArrayList[r*c];\n dis=new int[r*c];low=new int[r*c];\n for(int i=0;i<adjecent.length;i++)adjecent[i]=new ArrayList<>();\n visit=new boolean[r][c];\n int sum=0;\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[0].length;j++){\n sum+=grid[i][j];\n if(grid[i][j]==0||visit[i][j])continue;\n if(root==-1)root=i*grid[0].length+j;\n cnt++;\n dfs(grid,i,j);\n }\n }\n \n if(cnt>1)return 0;\n if(sum<=2)return sum;\n\t\t\n for(int i=0;i<grid.length;i++){//build the graph\n for(int j=0;j<grid[0].length;j++){\n if(grid[i][j]==0)continue;\n mark(grid,i,j,i+1,j);\n mark(grid,i,j,i-1,j);\n mark(grid,i,j,i,j+1);\n mark(grid,i,j,i,j-1);\n }\n }\n tarjan(-1,root);\n \n if(cut)return 1;\n return 2;\n \n \n }\n \n public void tarjan(int p,int r){\n if(cut)return;\n List<Integer>childs=adjecent[r];\n dis[r]=low[r]=time;\n time++;\n\n //core for tarjan, finding critical point\n int son=0;\n for(int c:childs){\n if(c==p)continue;\n if(dis[c]==0){\n son++;\n tarjan(r,c);\n low[r]=Math.min(low[r],low[c]);\n if((r==root&&son>1)||(low[c]>=dis[r]&&r!=root)){\n cut=true;\n return;\n }\n }else{\n if(c!=p){\n low[r]=Math.min(low[r],dis[c]);\n }\n }\n }\n\n }\n \n public void mark(int grid[][],int r,int c,int r1,int c1){\n if(r1<0||c1<0||r1>=grid.length||c1>=grid[0].length)return;\n if(grid[r1][c1]==0)return;\n \n int id1=r*grid[0].length+c;\n int id2=r1*grid[0].length+c1;\n adjecent[id1].add(id2);\n adjecent[id2].add(id1);\n \n }\n \n public void dfs(int grid[][],int i,int j){\n if(i<0||j<0||i>=grid.length||j>=grid[0].length)return;\n if(grid[i][j]==0)return;\n if(visit[i][j])return;\n visit[i][j]=true;\n dfs(grid,i+1,j);\n dfs(grid,i-1,j);\n dfs(grid,i,j+1);\n dfs(grid,i,j-1);\n }\n}\n``` | 7 | 0 | [] | 5 |
minimum-number-of-days-to-disconnect-island | Beats 80% || Easy to Understand C++ Code || DFS traversal | beats-80-easy-to-understand-c-code-dfs-t-nuf1 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe code checks if the grid of 1s (land) is already disconnected. If not, it tries to d | jitenagarwal20 | NORMAL | 2024-08-11T08:45:11.630848+00:00 | 2024-08-11T08:45:11.630872+00:00 | 689 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code checks if the grid of 1s (land) is already disconnected. If not, it tries to disconnect the grid by removing one 1 at a time. If removing a single 1 disconnects the grid, it returns 1. Otherwise, if no single removal works, it returns 2, indicating at least two changes are required to disconnect the grid.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1.Initial Check:** \nThe first step is to check if the grid is already disconnected. If the grid is initially disconnected, the answer is 0 days, as no changes are required.\n\n**2.DFS for Connectivity Check:**\nA Depth-First Search (DFS) is used to explore and mark connected components of 1s in the grid. The function isConnected performs this check.\nThe function dfs marks all 1s that belong to the same connected component by setting them to 0, ensuring that subsequent searches don\'t re-count the same component.\n\n**3.Check for Single-Day Disconnection:**\nAfter confirming that the grid is initially connected, the next step is to try disconnecting the grid by changing each 1 to 0 one by one.\nFor each 1 in the grid, the code temporarily sets it to 0 and checks if the grid becomes disconnected using the isConnected function.\nIf removing a single 1 causes the grid to become disconnected, the function returns 1, meaning the grid can be disconnected in one day.\n\n**4.Two-Day Disconnection:**\nIf no single 1 can disconnect the grid, the code concludes that at least two changes are required to disconnect the grid, so it returns 2.\n\n# Complexity\n- Time complexity: $$O((n\xD7m)2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n+m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int n,m;\n int dr[4]={0,0,1,-1},dc[4]={1,-1,0,0};\n void dfs(int r,int c,vector<vector<int>> &mat){\n mat[r][c]=0;\n for(int k=0;k<4;k++){\n int nr = r + dr[k],nc = c + dc[k];\n if(nr>=0 && nr<n && nc>=0 && nc<m && mat[nr][nc]==1)\n dfs(nr,nc,mat);\n }\n }\n bool isConnected(vector<vector<int>> mat){\n bool ans = false;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(mat[i][j]==1 && !ans){\n ans=true;\n dfs(i,j,mat);\n }\n else if(mat[i][j]==1 && ans)\n return false;\n }\n }\n return ans;\n }\n int minDays(vector<vector<int>>& grid) {\n n = grid.size(), m = grid[0].size();\n if(!isConnected(grid))\n return 0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1){\n grid[i][j]=0;\n if(!isConnected(grid))\n return 1;\n grid[i][j]=1;\n }\n }\n }\n return 2;\n }\n};\n``` | 6 | 0 | ['Depth-First Search', 'C++'] | 2 |
minimum-number-of-days-to-disconnect-island | 🔥 100% beats | DFS or Tarjan's Algorithm | | 100-beats-dfs-or-tarjans-algorithm-by-b_-yq3c | Solution 1 (DFS)\n# Intuition\nThe problem aims to find the minimum number of days required to disconnect a grid of islands (where each cell represents a piece | B_I_T | NORMAL | 2024-08-11T07:46:27.097331+00:00 | 2024-08-11T07:49:21.817937+00:00 | 808 | false | # Solution 1 (DFS)\n# Intuition\nThe problem aims to find the minimum number of days required to disconnect a grid of islands (where each cell represents a piece of land or water). The strategy revolves around assessing whether the grid is already disconnected, and if not, determining how quickly the disconnection can be achieved by removing cells.\n\n# Approach\n1. Initial Island Count:\n - First, count the number of islands in the grid. If there are multiple islands or no islands, return 0 immediately, because the grid is either already disconnected or empty.\n2. Single Cell Removal Check:\n - If there is only one island, try removing one land cell (1) at a time. After each removal, check the number of islands again. If removing a single cell leads to more than one island, return 1, because the grid becomes disconnected with just one removal.\n3. Two Cells Removal:\n - If removing one cell doesn\'t disconnect the grid, return 2, because removing two cells will always disconnect the grid. This is based on the fact that any connected landmass can be disconnected by removing at most two strategically chosen cells.\n# Complexity\n- Time Complexity:\n - The DFS for finding the number of islands takes O(N * M) where N is the number of rows and M is the number of columns.\n - In the worst case, where the grid has only one island, we might need to try removing each cell, leading to O(N * M * (N * M)) in the worst-case scenario.\n- Space Complexity:\n - The space complexity is O(N * M) due to the auxiliary vis array used during DFS.\n# Code\n```C++ []\nclass Solution {\nprivate:\n vector<int> X = {-1,0,1,0};\n vector<int> Y = {0,1,0,-1};\n bool isBoundary(int i,int j,int n,int m){\n return (i>=0 && j>=0 && i<n && j<m);\n }\n void dfs(int i,int j,vector<vector<int>> &grid,vector<vector<bool>> & vis){\n vis[i][j] = true;\n for(int k=0; k<4;k++){\n int ii=i+X[k];\n int jj=j+Y[k];\n if(isBoundary(ii,jj,grid.size(),grid[0].size()) \n && grid[ii][jj] == 1 && !vis[ii][jj]){\n dfs(ii,jj,grid,vis);\n }\n }\n }\n int getIslands(vector<vector<int>> & grid){\n int n=grid.size(),m=grid[0].size(),cnt=0;\n vector<vector<bool>> vis(n,vector<bool>(m,false));\n\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(grid[i][j]==1 && !vis[i][j]){\n cnt++;\n dfs(i,j,grid,vis);\n }\n }\n }\n return cnt;\n }\npublic:\n int minDays(vector<vector<int>>& grid) {\n if(getIslands(grid) != 1) return 0;\n\n for(int i=0; i<grid.size(); i++){\n for(int j=0; j<grid[0].size(); j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n if(getIslands(grid) != 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n};\n```\n```Java []\nclass Solution {\n private int[] X = {-1, 0, 1, 0};\n private int[] Y = {0, 1, 0, -1};\n\n private boolean isBoundary(int i, int j, int n, int m) {\n return i >= 0 && j >= 0 && i < n && j < m;\n }\n\n private void dfs(int i, int j, int[][] grid, boolean[][] vis) {\n vis[i][j] = true;\n for (int k = 0; k < 4; k++) {\n int ii = i + X[k];\n int jj = j + Y[k];\n if (isBoundary(ii, jj, grid.length, grid[0].length) \n && grid[ii][jj] == 1 && !vis[ii][jj]) {\n dfs(ii, jj, grid, vis);\n }\n }\n }\n\n private int getIslands(int[][] grid) {\n int n = grid.length, m = grid[0].length, cnt = 0;\n boolean[][] vis = new boolean[n][m];\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 && !vis[i][j]) {\n cnt++;\n dfs(i, j, grid, vis);\n }\n }\n }\n return cnt;\n }\n\n public int minDays(int[][] grid) {\n if (getIslands(grid) != 1) return 0;\n\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (getIslands(grid) != 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n}\n\n```\n```Python []\nclass Solution:\n def __init__(self):\n self.X = [-1, 0, 1, 0]\n self.Y = [0, 1, 0, -1]\n\n def isBoundary(self, i, j, n, m):\n return 0 <= i < n and 0 <= j < m\n\n def dfs(self, i, j, grid, vis):\n vis[i][j] = True\n for k in range(4):\n ii = i + self.X[k]\n jj = j + self.Y[k]\n if self.isBoundary(ii, jj, len(grid), len(grid[0])) and grid[ii][jj] == 1 and not vis[ii][jj]:\n self.dfs(ii, jj, grid, vis)\n\n def getIslands(self, grid):\n n, m = len(grid), len(grid[0])\n cnt = 0\n vis = [[False] * m for _ in range(n)]\n\n for i in range(n):\n for j in range(m):\n if grid[i][j] == 1 and not vis[i][j]:\n cnt += 1\n self.dfs(i, j, grid, vis)\n\n return cnt\n\n def minDays(self, grid):\n if self.getIslands(grid) != 1:\n return 0\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n grid[i][j] = 0\n if self.getIslands(grid) != 1:\n return 1\n grid[i][j] = 1\n\n return 2\n\n```\n```JavaScript []\nvar minDays = function(grid) {\n const X = [-1, 0, 1, 0];\n const Y = [0, 1, 0, -1];\n\n const isBoundary = (i, j, n, m) => {\n return i >= 0 && j >= 0 && i < n && j < m;\n };\n\n const dfs = (i, j, grid, vis) => {\n vis[i][j] = true;\n for (let k = 0; k < 4; k++) {\n const ii = i + X[k];\n const jj = j + Y[k];\n if (isBoundary(ii, jj, grid.length, grid[0].length) && grid[ii][jj] === 1 && !vis[ii][jj]) {\n dfs(ii, jj, grid, vis);\n }\n }\n };\n\n const getIslands = (grid) => {\n const n = grid.length, m = grid[0].length;\n let cnt = 0;\n const vis = Array.from({ length: n }, () => Array(m).fill(false));\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (grid[i][j] === 1 && !vis[i][j]) {\n cnt++;\n dfs(i, j, grid, vis);\n }\n }\n }\n return cnt;\n };\n\n if (getIslands(grid) !== 1) return 0;\n\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0;\n if (getIslands(grid) !== 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n};\n\n```\n# Solution 2 (Tarjan\'s Algorithm)\n# Intuition\nThis solution is designed to determine the minimum number of days required to disconnect a grid of land (where each cell is either land 1 or water 0). The main idea revolves around using Tarjan\'s Algorithm to find articulation points in the grid. Articulation points are nodes that, when removed, increase the number of connected components in the graph. In this context, the graph is the grid, and the nodes are land cells.\n\n# Approach\n1. Tarjan\u2019s Algorithm for Articulation Points:\n\n - Discovery Time: When a node is first visited, it is assigned a discovery time.\n - Low Value: The lowest discovery time reachable from that node, considering all back edges and descendants.\n - The algorithm recursively visits each node, updating low values and identifying articulation points based on the conditions:\n - A root node is an articulation point if it has more than one child.\n - A non-root node is an articulation point if there exists a child such that no vertex in the subtree rooted at the child can connect to an ancestor of the node via a back edge.\n2. Check for Articulation:\n\n - Traverse the grid, marking visited nodes and their discovery times.\n - Apply Tarjan\'s algorithm to identify any articulation points. If any articulation point is found, returning 1 is sufficient since removing it will disconnect the grid.\n - If no articulation points are found, but the grid was connected (i.e., no early exit with 0), return 2.\n3. Special Cases:\n\n - If the grid is already disconnected at the start, return 0.\n - If only one or two cells are connected, the function directly returns 0 or 1, respectively.\n# Complexity\n- Time Complexity: O(N * M), where N is the number of rows and M is the number of columns. This is due to Tarjan\u2019s DFS traversal of the entire grid.\n- Space Complexity: O(N * M) for the vis, low, and grid arrays.\n\n# Code\n```C++ []\nclass Solution {\nprivate:\n vector<int> X = {-1,0,1,0};\n vector<int> Y = {0,1,0,-1};\n vector<vector<int>> vis,low;\n int time;\n bool art=false;\n int n,m;\n bool isBoundary(int i,int j,int n,int m){\n return (i>=0 && j>=0 && i<n && j<m);\n }\n void isArti(int i,int j,int pi,int pj,vector<vector<int>> &grid){\n grid[i][j] = 0;\n int child = 0;\n low[i][j] = time;\n vis[i][j] = time;\n time++;\n\n for(int k=0;k<4; k++){\n int ii= i+X[k];\n int jj= j+Y[k];\n\n if(!isBoundary(ii,jj,n,m) || \n (ii==pi && jj==pj) || \n (grid[ii][jj] == 0 && vis[ii][jj] == 0)) continue;\n\n if(vis[ii][jj] == 0){\n child++;\n isArti(ii,jj,i,j,grid);\n low[i][j] = min(low[i][j],low[ii][jj]);\n if(vis[i][j] <= low[ii][jj] && pi != -200 && pj != -200)\n art = true;\n }else{\n low[i][j] = min(low[i][j],vis[ii][jj]);\n }\n }\n if(pi == -200 && pj == -200 && child > 1) art = true;\n }\npublic:\n int minDays(vector<vector<int>>& grid) {\n ios::sync_with_stdio(0);\n cin.tie(0);\n \n bool found = false;\n n = grid.size();\n m=grid[0].size();\n low = vector<vector<int>>(n,vector<int>(m,0));\n vis = vector<vector<int>>(n,vector<int>(m,0));\n time = 1;\n\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(grid[i][j]==1){\n if(found) return 0;\n found = true;\n isArti(i,j,-200,-200,grid);\n }\n }\n }\n if(time == 1) return 0;\n if(time == 2) return 1;\n\n if(art) return 1;\n else return 2;\n }\n};\n```\n```Java []\nclass Solution {\n private int[] X = {-1, 0, 1, 0};\n private int[] Y = {0, 1, 0, -1};\n private int[][] vis, low;\n private int time;\n private boolean art = false;\n private int n, m;\n\n private boolean isBoundary(int i, int j, int n, int m) {\n return i >= 0 && j >= 0 && i < n && j < m;\n }\n\n private void isArti(int i, int j, int pi, int pj, int[][] grid) {\n grid[i][j] = 0;\n int child = 0;\n low[i][j] = time;\n vis[i][j] = time;\n time++;\n\n for (int k = 0; k < 4; k++) {\n int ii = i + X[k];\n int jj = j + Y[k];\n\n if (!isBoundary(ii, jj, n, m) || \n (ii == pi && jj == pj) || \n (grid[ii][jj] == 0 && vis[ii][jj] == 0)) continue;\n\n if (vis[ii][jj] == 0) {\n child++;\n isArti(ii, jj, i, j, grid);\n low[i][j] = Math.min(low[i][j], low[ii][jj]);\n if (vis[i][j] <= low[ii][jj] && pi != -200 && pj != -200)\n art = true;\n } else {\n low[i][j] = Math.min(low[i][j], vis[ii][jj]);\n }\n }\n if (pi == -200 && pj == -200 && child > 1) art = true;\n }\n\n public int minDays(int[][] grid) {\n n = grid.length;\n m = grid[0].length;\n low = new int[n][m];\n vis = new int[n][m];\n time = 1;\n boolean found = false;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n if (found) return 0;\n found = true;\n isArti(i, j, -200, -200, grid);\n }\n }\n }\n if (time == 1) return 0;\n if (time == 2) return 1;\n\n return art ? 1 : 2;\n }\n}\n\n```\n```Python []\nclass Solution:\n def __init__(self):\n self.X = [-1, 0, 1, 0]\n self.Y = [0, 1, 0, -1]\n self.vis = []\n self.low = []\n self.time = 0\n self.art = False\n self.n = 0\n self.m = 0\n\n def isBoundary(self, i, j, n, m):\n return 0 <= i < n and 0 <= j < m\n\n def isArti(self, i, j, pi, pj, grid):\n grid[i][j] = 0\n child = 0\n self.low[i][j] = self.time\n self.vis[i][j] = self.time\n self.time += 1\n\n for k in range(4):\n ii = i + self.X[k]\n jj = j + self.Y[k]\n\n if not self.isBoundary(ii, jj, self.n, self.m) or \\\n (ii == pi and jj == pj) or \\\n (grid[ii][jj] == 0 and self.vis[ii][jj] == 0):\n continue\n\n if self.vis[ii][jj] == 0:\n child += 1\n self.isArti(ii, jj, i, j, grid)\n self.low[i][j] = min(self.low[i][j], self.low[ii][jj])\n if self.vis[i][j] <= self.low[ii][jj] and pi != -200 and pj != -200:\n self.art = True\n else:\n self.low[i][j] = min(self.low[i][j], self.vis[ii][jj])\n\n if pi == -200 and pj == -200 and child > 1:\n self.art = True\n\n def minDays(self, grid):\n self.n = len(grid)\n self.m = len(grid[0])\n self.low = [[0] * self.m for _ in range(self.n)]\n self.vis = [[0] * self.m for _ in range(self.n)]\n self.time = 1\n found = False\n\n for i in range(self.n):\n for j in range(self.m):\n if grid[i][j] == 1:\n if found:\n return 0\n found = True\n self.isArti(i, j, -200, -200, grid)\n \n if self.time == 1:\n return 0\n if self.time == 2:\n return 1\n\n return 1 if self.art else 2\n\n```\n```JavaScript []\nvar minDays = function(grid) {\n const n = grid.length;\n const m = grid[0].length;\n\n // Direction vectors for traversing the grid\n const directions = [\n [-1, 0], [1, 0], [0, -1], [0, 1]\n ];\n\n const isInBounds = (i, j) => i >= 0 && i < n && j >= 0 && j < m;\n\n // A utility function for DFS traversal to count the number of islands\n const dfs = (i, j, grid, visited) => {\n visited[i][j] = true;\n\n for (const [di, dj] of directions) {\n const ni = i + di;\n const nj = j + dj;\n if (isInBounds(ni, nj) && grid[ni][nj] === 1 && !visited[ni][nj]) {\n dfs(ni, nj, grid, visited);\n }\n }\n };\n\n const countIslands = (grid) => {\n const visited = Array.from({ length: n }, () => Array(m).fill(false));\n let islandCount = 0;\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (grid[i][j] === 1 && !visited[i][j]) {\n islandCount++;\n if (islandCount > 1) return islandCount;\n dfs(i, j, grid, visited);\n }\n }\n }\n return islandCount;\n };\n\n // Case 0: Check if the grid is already disconnected\n if (countIslands(grid) !== 1) return 0;\n\n // Case 1: Try removing one cell\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0;\n if (countIslands(grid) !== 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n // Case 2: If removing one cell doesn\'t work, it takes two cells\n return 2;\n};\n\n\n```\n# Upvote \n | 6 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'Strongly Connected Component', 'Python', 'C++', 'Java', 'JavaScript'] | 1 |
minimum-number-of-days-to-disconnect-island | Java BFS | java-bfs-by-hobiter-154x | If you look carefully, the result is 0, 1, or 2;\n1, if num of islands not 1, reutrn 0;\n2, special cases, only one 1 or two 1s;\n3, try to remove any 1 that ha | hobiter | NORMAL | 2020-08-30T04:21:06.591932+00:00 | 2020-08-31T17:34:58.374344+00:00 | 574 | false | If you look carefully, the result is 0, 1, or 2;\n1, if num of islands not 1, reutrn 0;\n2, special cases, only one 1 or two 1s;\n3, try to remove any 1 that has more than 1 neighbors, if it splits the islands, return 1;\n4, otherwise return 2;\n\n```\nclass Solution {\n Queue<int[]> connects;\n public int minDays(int[][] g) {\n int m = g.length, n = g[0].length, ones = 0, dir[][] = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n connects = new LinkedList<>();\n if (getNumOfIslandsAndConnects(g) != 1) return 0;\n for (int i = 0; i < m; i++) \n for (int j = 0; j < n; j++) ones += g[i][j];\n if (ones <= 2) return ones;\n while(!connects.isEmpty()) { // only check ones with neigs > 1, which potentially connects 2 islands\n int[] curr = connects.poll();\n g[curr[0]][curr[1]] = 0;\n if (getNumOfIslandsOnly(g) > 1) return 1;\n g[curr[0]][curr[1]] = 1;\n }\n return 2;\n }\n \n private int getNumOfIslandsAndConnects(int[][] g){\n return getNumOfIslands(g, true);\n }\n \n private int getNumOfIslandsOnly(int[][] g){\n return getNumOfIslands(g, false);\n }\n \n private int getNumOfIslands(int[][] g, boolean setConnects){\n int m = g.length, n = g[0].length, islands = 0, dir[][] = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n boolean[][] vs = new boolean[m][n];\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (g[i][j] == 0 || vs[i][j]) continue;\n islands++;\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[]{i, j});\n vs[i][j] = true;\n while (!q.isEmpty()) {\n int[] cur = q.poll();\n int numOfNeigs = 0;\n for(int[] d : dir) {\n int row = cur[0] + d[0], col = cur[1] + d[1];\n if (row < 0 || row >= m || col < 0 || col >= n || g[row][col] == 0) continue;\n numOfNeigs++;\n if (vs[row][col]) continue;\n vs[row][col] = true;\n q.offer(new int[]{row, col});\n }\n if (setConnects && numOfNeigs > 1) connects.offer(cur); // connects has more than 1 neighbors\n }\n }\n }\n return islands;\n }\n}\n``` | 6 | 3 | [] | 4 |
minimum-number-of-days-to-disconnect-island | Runtime beats 72.84%, Memory beats 89.20% [EXPLAINED] | runtime-beats-7284-memory-beats-8920-exp-qise | Intuition\nThe problem is about finding the minimum number of days needed to disconnect a single island in a grid where 1s represent land and 0s represent water | r9n | NORMAL | 2024-10-01T02:38:51.679188+00:00 | 2024-10-01T02:38:51.679228+00:00 | 11 | false | # Intuition\nThe problem is about finding the minimum number of days needed to disconnect a single island in a grid where 1s represent land and 0s represent water. An island is defined as a group of connected 1s, and we want to determine how to remove enough land cells to create multiple islands or completely empty the grid.\n\n# Approach\nFirst, find all land cells, color the first island to track it, and check if there are any other islands; if there\u2019s only one, try removing one land cell at a time to see if it disconnects the island, returning 1 if successful, otherwise return 2 if disconnection requires more moves.\n\n# Complexity\n- Time complexity:\nO(m * n) because we potentially traverse the entire grid multiple times, where m is the number of rows and n is the number of columns.\n\n- Space complexity:\nO(m * n) as well due to the need for a visited array to track the land cells, although the actual usage can vary depending on the implementation details.\n\n# Code\n```typescript []\ntype Direction = [number, number]; // Define a type for direction tuples\nconst directions: Direction[] = [[-1, 0], [1, 0], [0, -1], [0, 1]]; // Possible movement directions\n\nfunction minDays(grid: number[][]): number {\n let colorNumber = 2; // Start coloring islands with a unique number\n let landCells: [number, number][] = []; // Array to store coordinates of land cells\n\n // Function to color the island starting from (i, j)\n function colorIsland(i: number, j: number): void {\n grid[i][j] = colorNumber; // Color the current cell\n for (const [dx, dy] of directions) { // Iterate through all directions\n const newI = i + dx; // Calculate new row index\n const newJ = j + dy; // Calculate new column index\n \n // Check if the new position is valid and is part of the island\n if (newI >= 0 && newJ >= 0 && newI < grid.length && newJ < grid[0].length && grid[newI][newJ] && grid[newI][newJ] !== colorNumber) {\n colorIsland(newI, newJ); // Recursively color the connected cell\n }\n }\n }\n\n // Function to gather all land cells\' coordinates\n function addLandCells(): void {\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (grid[i][j]) { // If it\'s land\n landCells.push([i, j]); // Add the cell to the list\n }\n }\n }\n }\n\n // Function to check if there is another island in the grid\n function findAnotherIsland(): boolean {\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n // If it\'s land and not colored with the current color\n if (grid[i][j] && grid[i][j] !== colorNumber) {\n return true; // Found another island\n }\n }\n }\n return false; // No other islands found\n }\n\n addLandCells(); // Populate landCells with coordinates of land\n\n // If there are less than 2 land cells, return the number of land cells\n if (landCells.length < 2) {\n return landCells.length;\n }\n\n // Color the first island found\n colorIsland(landCells[0][0], landCells[0][1]);\n\n // If there is another island, return 0\n if (findAnotherIsland()) {\n return 0;\n }\n\n colorNumber++; // Increment color number for future coloring\n\n // Attempt to remove each land cell and check if the grid becomes disconnected\n for (let i = 0; i < landCells.length; i++) {\n grid[landCells[i][0]][landCells[i][1]] = 0; // Temporarily remove the land cell\n // Color the next cell in the list\n colorIsland(landCells[(i + 1) % landCells.length][0], landCells[(i + 1) % landCells.length][1]);\n \n // Check if there\'s another island\n if (findAnotherIsland()) {\n return 1; // Grid becomes disconnected\n }\n\n grid[landCells[i][0]][landCells[i][1]] = colorNumber; // Restore the land cell with the current color\n colorNumber++; // Increment color for the next iteration\n }\n\n return 2; // It takes 2 days to disconnect the island\n}\n\n``` | 5 | 0 | ['TypeScript'] | 0 |
minimum-number-of-days-to-disconnect-island | DFS solution with Intuition 🚀| Beginner's Approach | dfs-solution-with-intuition-beginners-ap-3dcx | Intuition\n Describe your first thoughts on how to solve this problem. \nIf we cut an island from any corner leaving smalllest possible island, we need two 0 in | hemantsingh_here | NORMAL | 2024-08-11T16:43:40.479488+00:00 | 2024-08-11T16:43:40.479520+00:00 | 209 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf we cut an island from any corner leaving smalllest possible island, we need two 0 in diagonal setting. \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIf number of island is 1, then we flip all 1 to 0 by one by one and now check if island is disconnected, if not then we undo the operation, flip the next 1\n\n\n# Code\n```\nclass Solution {\npublic:\n\n void dfs(int i, int j,vector<vector<int>> &visited, int m, int n,vector<vector<int>>& grid ){\n if(i<0 || i >= m || j < 0 || j >= n || visited[i][j] == 1 || grid[i][j] == 0){\n return;\n }\n\n visited[i][j] = 1;\n\n dfs(i+1,j,visited,m,n,grid);\n dfs(i-1,j,visited,m,n,grid);\n dfs(i,j+1,visited,m,n,grid);\n dfs(i,j-1,visited,m,n,grid);\n }\n\n int islandcount(vector<vector<int>>& grid){\n int m = grid.size();\n int n = grid[0].size();\n\n vector<vector<int>> visited(m,vector<int>(n,0));\n int islands = 0;\n for(int i = 0; i < m; i++){\n for(int j =0; j<n; j++){\n if(grid[i][j] == 1 && visited[i][j] == 0){\n dfs(i,j,visited,m,n,grid);\n islands++;\n }\n }\n }\n return islands;\n }\n\n int minDays(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n\n int islands = islandcount(grid);\n\n\n if(islands > 1 || islands == 0){\n return 0;\n }\n\n for(int i= 0; i<m; i++){\n for(int j =0; j<n; j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n islands = islandcount(grid);\n\n if(islands > 1 || islands == 0){\n return 1;\n }\n // backtrack \n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n};\n``` | 5 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | ✅✅ BFS Solution || CPP 🚀🚀 | bfs-solution-cpp-by-baragemanish6258-jmlj | \n# Code\n\nclass Solution {\npublic:\n int dx[4] = {-1,0,1,0};\n int dy[4] = {0,1,0,-1};\n\n int gc = 0;\n\n int solve(vector<vector<int>>& grid)\n | baragemanish6258 | NORMAL | 2024-08-11T06:35:16.510545+00:00 | 2024-08-11T06:35:16.510595+00:00 | 995 | false | \n# Code\n```\nclass Solution {\npublic:\n int dx[4] = {-1,0,1,0};\n int dy[4] = {0,1,0,-1};\n\n int gc = 0;\n\n int solve(vector<vector<int>>& grid)\n {\n int n = grid.size();\n int m = grid[0].size();\n\n vector<vector<int>>vis(n, vector<int>(m, 0));\n queue<pair<int,int>>q;\n int cnt =0;\n\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(grid[i][j] == 1 && !vis[i][j])\n {\n\n cnt++;\n\n q.push({i,j});\n vis[i][j] = 1;\n\n while(!q.empty())\n {\n int r = q.front().first;\n int c = q.front().second;\n\n q.pop();\n gc++;\n\n for(int i=0;i<4;i++)\n {\n int nx = r + dx[i];\n int ny = c + dy[i];\n\n if(nx>=0 && nx<n && ny>=0 && ny<m && grid[nx][ny] == 1 && !vis[nx][ny])\n {\n q.push({nx,ny});\n vis[nx][ny] = 1;\n }\n }\n\n\n }\n \n }\n }\n }\n\n\n return cnt;\n\n }\n int minDays(vector<vector<int>>& grid) {\n \n int n = grid.size();\n int m = grid[0].size();\n\n int tot = solve(grid);\n\n if(tot==1 && gc ==1)\n {\n return 1;\n }\n if(tot > 1 || tot==0)\n {\n return 0;\n }\n\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(grid[i][j] == 1)\n {\n grid[i][j] = 0;\n\n int cnt = solve(grid);\n\n if(cnt >1)\n {\n return 1;\n }\n\n grid[i][j] =1;\n }\n }\n }\n\n return 2;\n\n }\n};\n``` | 5 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'C++'] | 3 |
minimum-number-of-days-to-disconnect-island | Python | DFS | python-dfs-by-khosiyat-72pp | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n def is_connected(grid):\n | Khosiyat | NORMAL | 2024-08-11T05:12:30.314191+00:00 | 2024-08-11T05:12:30.314212+00:00 | 665 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/submissions/1351676215/?envType=daily-question&envId=2024-08-11)\n\n# Code\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n def is_connected(grid):\n visited = [[False]*n for _ in range(m)]\n def dfs(x, y):\n visited[x][y] = True\n for dx, dy in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n nx, ny = x + dx, y + dy\n if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny] and grid[nx][ny] == 1:\n dfs(nx, ny)\n \n found = False\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and not visited[i][j]:\n if found:\n return False # found another island\n found = True\n dfs(i, j)\n return found\n \n def count_islands(grid):\n count = 0\n visited = [[False]*n for _ in range(m)]\n def dfs(x, y):\n visited[x][y] = True\n for dx, dy in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n nx, ny = x + dx, y + dy\n if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny] and grid[nx][ny] == 1:\n dfs(nx, ny)\n \n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and not visited[i][j]:\n count += 1\n dfs(i, j)\n return count\n \n m, n = len(grid), len(grid[0])\n \n # If grid is already disconnected\n if count_islands(grid) != 1:\n return 0\n \n # Try to disconnect by removing one cell\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n grid[i][j] = 0\n if count_islands(grid) != 1:\n return 1\n grid[i][j] = 1\n \n # If we need to remove two cells\n return 2\n\n```\n\n# Minimum Days to Disconnect Grid\n\n## Key Ideas:\n\n### Grid Connectivity:\n- If the grid is already disconnected, return `0`.\n- If removing any one land cell disconnects the grid, return `1`.\n- If removing one cell doesn\'t disconnect the grid, check if removing two cells can achieve disconnection.\n\n### DFS (Depth-First Search):\n- We\'ll use DFS to check if the grid is connected (i.e., only one island exists).\n- We\'ll also use DFS to simulate the removal of land cells and check the effect.\n\n### Handling Special Cases:\n- If the grid has only one land cell, it will require `1` day to disconnect it.\n- If the grid has more than one land cell, explore options by removing one or two cells.\n\n## Explanation:\n- `is_connected` function checks if there is exactly one island in the grid by performing a DFS traversal.\n- `count_islands` counts how many separate islands exist in the grid.\n- The main function first checks if the grid is already disconnected. If so, it returns `0`. If the grid is connected, we simulate removing one cell at a time and check if the grid gets disconnected. If so, return `1`. If not, the minimum is `2`, because removing two cells will certainly disconnect the grid.\n\n## Example Outputs:\n- For `grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]`, the output is `2`.\n- For `grid = [[1,1]]`, the output is `2`.\n\n\n | 5 | 1 | ['Python3'] | 1 |
minimum-number-of-days-to-disconnect-island | Tarjan's Algorithm | tarjans-algorithm-by-anand_shukla1312-l8vb | Intuition\n Describe your first thoughts on how to solve this problem. \nAn articulation point is a cell that will split an island in two when it is changed fro | anand_shukla1312 | NORMAL | 2024-08-11T03:40:05.521981+00:00 | 2024-08-11T03:40:05.522003+00:00 | 639 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAn articulation point is a cell that will split an island in two when it is changed from land to water. If a given grid has an articulation point, we can disconnect the island in one day. Tarjan\'s algorithm efficiently finds articulation points in a graph.\n\n- The algorithm uses three key pieces of information for each node (cell): discovery time, lowest reachable time, and parent. The discovery time is when a node is first visited during the DFS. The lowest reachable time is the minimum discovery time of any node that can be reached from the subtree rooted at the current node, including the current node itself. The parent is the node from which the current node was discovered during the DFS.\n\n\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nA node can be an articulation point in two cases:\n\n1. A non-root node is an articulation point if it has a child whose lowest reachable time is greater than or equal to the node\'s discovery time. This condition means that the child (and its subtree) cannot reach any ancestor of the current node without going through the current node, making it critical for connectivity.\n2. The root node of the DFS tree is an articulation point if it has more than one child. Removing the root would disconnect these children from each other.\n\n If no articulation points are found, the grid cannot be disconnected by removing a single land cell. In that case, we return 2.\n\n---\n\n\n# Complexity\n- Time complexity: $$O(m * n)$$\n<!-- Add your time complexity here, e.g. -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n# Code\n```\nclass Solution {\n\n // Directions for adjacent cells: right, down, left, up\n private static final int[][] DIRECTIONS = {\n { 0, 1 },\n { 1, 0 },\n { 0, -1 },\n { -1, 0 },\n };\n\n public int minDays(int[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n ArticulationPointInfo apInfo = new ArticulationPointInfo(false, 0);\n int landCells = 0, islandCount = 0;\n\n // Arrays to store information for each cell\n int[][] discoveryTime = new int[rows][cols]; // Time when a cell is first discovered\n int[][] lowestReachable = new int[rows][cols]; // Lowest discovery time reachable from the subtree rooted at\n // this cell\n int[][] parentCell = new int[rows][cols]; // Parent of each cell in DFS tree\n\n // Initialize arrays with default values\n for (int i = 0; i < rows; i++) {\n Arrays.fill(discoveryTime[i], -1);\n Arrays.fill(lowestReachable[i], -1);\n Arrays.fill(parentCell[i], -1);\n }\n\n // Traverse the grid to find islands and articulation points\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n landCells++;\n if (discoveryTime[i][j] == -1) { // If not yet visited\n // Start DFS for a new island\n findArticulationPoints(\n grid,\n i,\n j,\n discoveryTime,\n lowestReachable,\n parentCell,\n apInfo\n );\n islandCount++;\n }\n }\n }\n }\n\n // Determine the minimum number of days to disconnect the grid\n if (islandCount == 0 || islandCount >= 2) return 0; // Already disconnected or no land\n if (landCells == 1) return 1; // Only one land cell\n if (apInfo.hasArticulationPoint) return 1; // An articulation point exists\n return 2; // Need to remove any two land cells\n }\n\n private void findArticulationPoints(\n int[][] grid,\n int row,\n int col,\n int[][] discoveryTime,\n int[][] lowestReachable,\n int[][] parentCell,\n ArticulationPointInfo apInfo\n ) {\n int rows = grid.length, cols = grid[0].length;\n discoveryTime[row][col] = apInfo.time;\n apInfo.time++;\n lowestReachable[row][col] = discoveryTime[row][col];\n int children = 0;\n\n // Explore all adjacent cells\n for (int[] direction : DIRECTIONS) {\n int newRow = row + direction[0];\n int newCol = col + direction[1];\n if (isValidLandCell(grid, newRow, newCol)) {\n if (discoveryTime[newRow][newCol] == -1) {\n children++;\n parentCell[newRow][newCol] = row * cols + col; // Set parent\n findArticulationPoints(\n grid,\n newRow,\n newCol,\n discoveryTime,\n lowestReachable,\n parentCell,\n apInfo\n );\n\n // Update lowest reachable time\n lowestReachable[row][col] = Math.min(\n lowestReachable[row][col],\n lowestReachable[newRow][newCol]\n );\n\n // Check for articulation point condition\n if (\n lowestReachable[newRow][newCol] >=\n discoveryTime[row][col] &&\n parentCell[row][col] != -1\n ) {\n apInfo.hasArticulationPoint = true;\n }\n } else if (newRow * cols + newCol != parentCell[row][col]) {\n // Update lowest reachable time for back edge\n lowestReachable[row][col] = Math.min(\n lowestReachable[row][col],\n discoveryTime[newRow][newCol]\n );\n }\n }\n }\n\n // Root of DFS tree is an articulation point if it has more than one child\n if (parentCell[row][col] == -1 && children > 1) {\n apInfo.hasArticulationPoint = true;\n }\n }\n\n // Check if the given cell is a valid land cell\n private boolean isValidLandCell(int[][] grid, int row, int col) {\n int rows = grid.length, cols = grid[0].length;\n return (\n row >= 0 &&\n col >= 0 &&\n row < rows &&\n col < cols &&\n grid[row][col] == 1\n );\n }\n\n private class ArticulationPointInfo {\n\n boolean hasArticulationPoint;\n int time;\n\n ArticulationPointInfo(boolean hasArticulationPoint, int time) {\n this.hasArticulationPoint = hasArticulationPoint;\n this.time = time;\n }\n }\n}\n```\n\n | 5 | 0 | ['Java'] | 2 |
minimum-number-of-days-to-disconnect-island | notes Explanation .... | notes-explanation-by-ankit1478-mf2s | Intuition\nsorry for Bad Handwriting..\n\n\n\n\n\n# Complexity\n- Time complexity: O(NM) + O(NM) = O(NM)\n Add your time complexity here, e.g. O(n) \n\n- Space | ankit1478 | NORMAL | 2024-03-05T10:31:42.926434+00:00 | 2024-03-05T10:32:34.445414+00:00 | 275 | false | # Intuition\nsorry for Bad Handwriting..\n\n\n\n\n\n# Complexity\n- Time complexity: O(NM) + O(NM) = O(N*M)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(NM) + O(NM) = O(N*M).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n \n public int minDays(int[][] grid) {\n if(noOfIsland(grid)!=1)return 0;\n int n = grid.length;\n int m = grid[0].length;\n\n for(int i =0;i<n;i++){\n for(int j =0;j<m;j++){\n if(grid[i][j]==1){\n grid[i][j] =0;\n if(noOfIsland(grid)!=1)return 1;\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n\n static int noOfIsland(int grid[][]){\n int ans =0;\n int n = grid.length;\n int m = grid[0].length;\n boolean vis[][] = new boolean[n][m];\n\n for(int i =0;i<n;i++){\n for(int j =0;j<m;j++){\n if(!vis[i][j] && grid[i][j]==1){\n ans++;\n dfs(grid,i,j,n,m ,vis);\n }\n }\n }\n return ans; \n }\n\n static void dfs(int grid[][] , int i , int j , int n , int m , boolean vis[][]){\n if(i<0 || j<0 || i==n || j==m || vis[i][j] || grid[i][j]==0)return ;\n\n vis[i][j] = true;\n dfs(grid,i+1,j,n,m,vis);\n dfs(grid,i-1,j,n,m,vis);\n dfs(grid,i,j+1,n,m,vis);\n dfs(grid,i,j-1,n,m,vis);\n }\n}\n``` | 5 | 0 | ['Depth-First Search', 'Java'] | 3 |
minimum-number-of-days-to-disconnect-island | Java || 2 Methods || Brute Force and Articulation Point | java-2-methods-brute-force-and-articulat-zrct | \n // b <================= Minimum Number of Days to Disconnect Island ==========>\n // https://leetcode.com/problems/minimum-number-of-days-to-disconnect | JoseDJ2010 | NORMAL | 2022-10-20T04:11:46.816692+00:00 | 2022-10-20T04:13:44.238288+00:00 | 535 | false | ```\n // b <================= Minimum Number of Days to Disconnect Island ==========>\n // https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/\n\n // ! Brute Force, passed since the test case and constraints are small.\n\n public static void dfs_numsIsland(int sr, int sc, int[][] grid, int[][] dir, boolean[][] vis) {\n vis[sr][sc] = true;\n\n for (int d = 0; d < dir.length; d++) {\n int r = sr + dir[d][0];\n int c = sc + dir[d][1];\n\n if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && grid[r][c] == 1 && !vis[r][c]) {\n dfs_numsIsland(r, c, grid, dir, vis);\n }\n }\n }\n\n public static int numOfIslands(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n boolean[][] vis = new boolean[n][m];\n\n int noOfIslands = 0;\n int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };\n for (int i = 0; i < n * m; i++) {\n int r = i / m, c = i % m;\n if (!vis[r][c] && grid[r][c] == 1) {\n dfs_numsIsland(r, c, grid, dir, vis);\n noOfIslands++;\n }\n }\n\n return noOfIslands;\n }\n\n public int minDays_(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n int initialComponents = numOfIslands(grid);\n if (initialComponents > 1 || initialComponents == 0)\n return 0;\n\n for (int i = 0; i < n * m; i++) {\n int r = i / m, c = i % m;\n\n if (grid[r][c] == 1) {\n grid[r][c] = 0;\n int noOfComponents = numOfIslands(grid);\n if (noOfComponents > 1 || noOfComponents == 0)\n return 1;\n grid[r][c] = 1;\n }\n }\n return 2;\n }\n\n // B Optimized using the articulation Point\n\n private static int[] low, disc;\n private static int time = 0;\n private static boolean[] vis;\n\n public static int dfs_size(int idx, int[][] grid, boolean[] vis) {\n int n = grid.length, m = grid[0].length;\n int sr = idx / m, sc = idx % m;\n\n vis[idx] = true;\n\n int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };\n int count = 0;\n\n for (int d = 0; d < dir.length; d++) {\n int r = sr + dir[d][0];\n int c = sc + dir[d][1];\n\n if (r >= 0 && c >= 0 && r < grid.length && c < grid[0].length && grid[r][c] == 1 && !vis[r * m + c]) {\n count += dfs_size(r * m + c, grid, vis);\n }\n }\n\n return count + 1;\n }\n\n public static boolean tarjans(int src, int par, int[][] grid) {\n int n = grid.length, m = grid[0].length;\n disc[src] = low[src] = time++;\n vis[src] = true;\n\n int[][] dir = { { 1, 0 }, { -1, 0 }, { 0, -1 }, { 0, 1 } };\n\n boolean res = false;\n for (int d = 0; d < dir.length; d++) {\n int sr = src / m, sc = src % m;\n\n int r = sr + dir[d][0];\n int c = sc + dir[d][1];\n\n if (r >= 0 && c >= 0 && r < n && c < m && grid[r][c] == 1) {\n int nbr = r * m + c;\n if (!vis[nbr]) {\n res = res || tarjans(nbr, src, grid);\n if (disc[src] < low[nbr]) { // Yahan pe equal to sign nhi kiya use. Why? ==> Kyunki hume cycle wale\n // structure ke liye bhi true return karna tha kyunki wahan pe do vertex\n // ko nikal ke graph disconnected ban sakta hai. Example is of a square,\n // removing the diagonal vertex will make component disconnected.\n return true;\n }\n low[src] = Math.min(low[nbr], low[src]);\n } else if (nbr != par) {\n low[src] = Math.min(low[src], disc[nbr]);\n }\n }\n\n }\n return res;\n }\n\n public int minDays(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n\n disc = new int[n * m];\n low = new int[n * m];\n vis = new boolean[n * m];\n int root = -1;\n int noOfComponents = 0, size = 0;\n for (int i = 0; i < n * m; i++) {\n int r = i / m, c = i % m;\n\n if (grid[r][c] == 1 && !vis[i]) {\n root = i;\n size += dfs_size(i, grid, vis);\n noOfComponents++;\n }\n }\n\n if (noOfComponents == 0 || noOfComponents > 1) // Agar mera component 0 hai ya 1 ha se bada hai to mai already\n // disconnected hun, to 0 retun kardo\n return 0;\n else if (size <= 2) // Ab kyunki mai uper component ka check karke aaya hun to mai sure hun ki ab ek\n // he single component hai graph mai. To agar component ka size 1 ya 2 hua, to\n // ` utne he din lagte use disconnect karne mai jitna size hota.\n return size;\n\n vis = new boolean[n * m];\n boolean res = tarjans(root, -1, grid);\n return res ? 1 : 2; // Ab agar mujhe articulation point milta hai to mai to mai 1 return kardunga,\n // aur agar nhi milta hai to mai 2 return kardunga kyunki at most mera answer 2\n // ho sakta hai.\n\n }\n```\n\n## Answer to Why at most can be the answer : \n\n\n\n## Some Notes on Articulation Point :\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n | 5 | 0 | ['Java'] | 1 |
minimum-number-of-days-to-disconnect-island | Easy to understand Clean Code || Depth-First-Search || C++ | easy-to-understand-clean-code-depth-firs-j0s9 | Intuition\nThe problem is about determining how quickly we can disconnect a single island into two or more separate pieces by changing land cells into water. A | Satvik_Agrawal | NORMAL | 2024-08-11T10:41:52.451580+00:00 | 2024-08-11T10:41:52.451606+00:00 | 301 | false | # Intuition\nThe problem is about determining how quickly we can disconnect a single island into two or more separate pieces by changing land cells into water. A disconnected grid either has multiple islands or no islands at all. The intuition is based on:\n1. **Counting Islands**: If the grid initially has more than one island, it is already disconnected, so no days are needed.\n2. **Single Island**: If there is a single island, the goal is to disconnect it by flipping a land cell to water and checking if the grid becomes disconnected.\n\n# Approach\n1. **Initial Check:**\n - First, count the number of islands in the grid. If the grid is already disconnected (more than one island or no islands), return 0 as no days are needed.\n2. **Try Disconnecting with One Flip:**\n - For each land cell (i, j) in the grid:\n - Temporarily turn the cell into water.\n - Recount the number of islands in the grid.\n - If the grid becomes disconnected (more than one island or no islands), return 1 (as only one day is needed).\n - Restore the cell back to land.\n3. **If Not Possible with One Flip:**\n - If after trying all single-cell flips the grid remains connected, return 2, because disconnecting the grid must require at least two days.\n\n# Complexity\n- Time complexity:\n - The time complexity is dominated by the need to count islands multiple times.\n - Counting islands itself is O(m * n) where m and n are the dimensions of the grid.\n - Since we may have to perform the island count for each land cell and potentially flip back and forth, the overall time complexity can be approximated as O(m * n * (m * n)) = $$O((m \\times n)^2)$$.\n\n- Space complexity:\n - The space complexity is $$O(m \\times n)$$ due to the auxiliary space used for DFS and to store the grid.\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(vector<vector<int>>& mat, int i, int j) {\n if (i < 0 || i >= mat.size() || j < 0 || j >= mat[0].size() ||\n mat[i][j] == 0)\n return;\n mat[i][j] = 0;\n dfs(mat, i + 1, j);\n dfs(mat, i - 1, j);\n dfs(mat, i, j + 1);\n dfs(mat, i, j - 1);\n }\n int countIslands(vector<vector<int>> grid) {\n int isl = 0;\n for(int i=0; i<grid.size(); i++) {\n for(int j=0; j<grid[0].size(); j++) {\n if(grid[i][j] == 1) {\n isl++;\n dfs(grid, i, j);\n }\n }\n }\n return isl;\n }\n int minDays(vector<vector<int>>& grid) {\n int n = countIslands(grid);\n if(n > 1 || n == 0) return 0;\n for(int i=0; i<grid.size(); i++) {\n for(int j=0; j<grid[0].size(); j++) {\n if(grid[i][j] == 1) {\n grid[i][j] = 0;\n int isl = countIslands(grid);\n if(isl>1 || isl==0) return 1;\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n};\n``` | 4 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | DCC-: 11 AUG 2024 || DFS. | dcc-11-aug-2024-dfs-by-sajaltiwari007-utqa | Problem Intuition and Approach\n\nThe problem aims to determine the minimum number of days required to disconnect an island on a grid by turning one or more lan | sajaltiwari007 | NORMAL | 2024-08-11T05:35:13.853118+00:00 | 2024-08-11T05:35:13.853190+00:00 | 270 | false | ### Problem Intuition and Approach\n\nThe problem aims to determine the minimum number of days required to disconnect an island on a grid by turning one or more land cells (`1`s) into water (`0`s). The grid is represented by a 2D array, where `1` indicates land and `0` indicates water. An island is a group of connected land cells, connected horizontally or vertically.\n\n#### Intuition:\n\n1. **Initial Island Count:**\n - First, we check how many islands are present in the grid. If there are no islands (`0` islands) or more than one island (`>1` islands) initially, the answer is `0` days since no disconnection is needed, or the grid is already disconnected.\n\n2. **Special Cases:**\n - If the grid has a single row or a single column (`n == 1` or `m == 1`), then the minimum number of days needed is `1` or `2`, based on whether the grid is a single connected land strip or not.\n\n3. **Simulate Disconnection:**\n - For each land cell in the grid, simulate changing it to water (`0`) and check the number of islands that result. \n - If removing any single land cell results in more than one island, the answer is `1` day, since the grid becomes disconnected by removing that cell.\n - If removing each single land cell does not disconnect the island, the answer is `2` days, because it takes more than one operation to disconnect the island.\n\n#### Step-by-Step Approach:\n\n1. **DFS to Count Islands:**\n - Use Depth-First Search (DFS) to count the number of islands initially.\n - If the number of islands is `0` or greater than `1`, return `0` days.\n\n2. **Edge Cases:**\n - For a grid of size `1x2` or `2x1`, return `2` days as the minimum to disconnect.\n\n3. **Iterate Over All Land Cells:**\n - For each land cell, temporarily change it to water (`0`), and count the number of islands again using DFS.\n - If at any point the number of islands becomes greater than `1`, return `1` day.\n - If no single land cell can disconnect the island, return `2` days.\n\n### Complexity Analysis\n\n1. **Time Complexity:**\n - **Initial Island Count (`O(n * m)`):** The grid is traversed once, and for each unvisited land cell, a DFS is performed, which in the worst case could visit all `n * m` cells.\n - **List Construction (`O(n * m)`):** The grid is traversed again to collect all land cells in a list.\n - **Simulate Disconnection (`O(n * m * n * m)`):** For each land cell, set it to water and check the island count, which involves traversing the grid again and performing DFS.\n\n - **Overall Time Complexity:** `O((n * m)^2)` (due to iterating over all cells and performing DFS for each).\n\n2. **Space Complexity:**\n - **Visited Array (`O(n * m)`):** The `visited` array is of size `n * m`.\n - **List of Land Cells (`O(n * m)`):** The list stores all the land cells, which can be up to `n * m` in size.\n - **DFS Recursion Stack (`O(n * m)`):** In the worst case, the DFS recursion stack could be `n * m` deep.\n\n - **Overall Space Complexity:** `O(n * m)`.\n\n### Conclusion:\n\n- **Approach Intuition:** The algorithm checks whether the grid is already disconnected or can be disconnected by changing one or two land cells into water.\n- **Time Complexity:** `O((n * m)^2)`, where `n` is the number of rows and `m` is the number of columns.\n- **Space Complexity:** `O(n * m)`.\n\n# Code\n```\nclass Solution {\n\n class Pair{\n int row;\n int col;\n Pair(int r,int c){\n this.row = r;\n this.col = c;\n }\n }\n public int minDays(int[][] grid){\n\n int number_of_islands=0;\n boolean[][] visited = new boolean[grid.length][grid[0].length]; // Space - O(n*m)\n int n = grid.length;\n int m = grid[0].length;\n\n //Time -: O(n*m) every cell is being visited only onces.\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n\n if(visited[i][j]==false && grid[i][j]==1){\n dfs(i,j,grid,visited);\n number_of_islands++;\n }\n }\n }\n if(number_of_islands>1 || number_of_islands==0) return 0;\n \n if(n==1 && m==2) return 2;\n if(m==1 && n==2) return 2;\n if(n==1 || m==1) return 1;\n\n visited = new boolean[grid.length][grid[0].length];\n List<Pair> list = new ArrayList<>(); // Space - : O(n*m) in the worst case;\n // Time -O(n*m)\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1) list.add(new Pair(i,j));\n }\n }\n if(list.size()==1) return 1;\n if(list.size()==n*m) return 2;\n \n // Time in the worst case = O(list.size()*n*m) or O(n*m*n*m)\n for(int ind=0;ind<list.size();ind++){\n\n Pair pair = list.get(ind);\n grid[pair.row][pair.col]=0;\n visited = new boolean[grid.length][grid[0].length];\n number_of_islands=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n\n if(visited[i][j]==false && grid[i][j]==1){\n dfs(i,j,grid,visited);\n number_of_islands++;\n }\n }\n }\n if(number_of_islands>1) return 1;\n grid[pair.row][pair.col]=1;\n }\n\n return 2;\n\n }\n // Plain DFS \n // Recursion Stack Space-: O(n*m)\n void dfs(int row , int col , int[][] grid , boolean[][] visited){\n\n visited[row][col]=true;\n\n int[] r = {0,0,1,-1};\n int[] c = {1,-1,0,0};\n for(int i=0;i<4;i++){\n\n int rr = row+r[i];\n int cc = col+c[i];\n if(rr>=0 && rr<grid.length && cc>=0 && cc<grid[0].length && grid[rr][cc]==1 && visited[rr][cc]==false){\n dfs(rr,cc,grid,visited);\n }\n }\n }\n}\n``` | 4 | 0 | ['Depth-First Search', 'Java'] | 1 |
minimum-number-of-days-to-disconnect-island | Most --SIMPLIFIED-- using dfs stack -- EXPLAINED fully | most-simplified-using-dfs-stack-explaine-9lxf | Approach\n Describe your approach to solving the problem. \n\ncheck starting\n\n- count islands: first, count how many separate islands are in the grid. if ther | pawansingh275701 | NORMAL | 2024-08-11T01:14:25.459794+00:00 | 2024-08-11T01:14:25.459818+00:00 | 61 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n\n*check starting*\n\n- **count islands**: first, count how many separate islands are in the grid. if there are already multiple islands (or none), return 0 because no single cell removal is needed to disconnect them.\ntest each cell removal:\n\n---\n\n\n**try** removing each land cell: for each land cell (value 1), temporarily remove it (set it to 0).\n- re-check islands: after removing the cell, count the number of islands again. if removing this cell splits the island into more than one island, return 1 because it means one cell removal is enough to disconnect the island.\nrestore the cell: put the cell back and continue with the next cell.\nif no single cell works:\n\ndefault to two days: if no single cell removal can split the island, then it would take at least two days for disconnection. so, return 2.\n\n*hope you understand i have tried my best i have tried bfs but didn\'t worked it your worked let me know.*\n\n# Code\n```\nclass Solution {\n int M, N;\n vector<int> dx = {0, 0, 1, -1};\n vector<int> dy = {1, -1, 0, 0};\n\n void dfs(vector<vector<int>>& grid, int x, int y, vector<vector<bool>>& visited) {\n stack<pair<int, int>> s;\n s.push({x, y});\n visited[x][y] = true;\n while (!s.empty()) {\n auto [cx, cy] = s.top(); s.pop();\n for (int d = 0; d < 4; ++d) {\n int nx = cx + dx[d], ny = cy + dy[d];\n if (nx >= 0 && nx < M && ny >= 0 && ny < N && grid[nx][ny] == 1 && !visited[nx][ny]) {\n visited[nx][ny] = true;\n s.push({nx, ny});\n }\n }\n }\n }\n\n bool hasSingleIsland(vector<vector<int>>& grid) {\n vector<vector<bool>> visited(M, vector<bool>(N, false));\n int count = 0;\n for (int i = 0; i < M; ++i) {\n for (int j = 0; j < N; ++j) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n if (++count > 1) return false;\n dfs(grid, i, j, visited);\n }\n }\n }\n return count == 1;\n }\n\npublic:\n int minDays(vector<vector<int>>& grid) {\n M = grid.size();\n N = grid[0].size();\n \n \n if (!hasSingleIsland(grid)) return 0;\n\n // try removing each cell and check the number of islands\n for (int i = 0; i < M; ++i) {\n for (int j = 0; j < N; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0; // remove cell\n if (!hasSingleIsland(grid)) return 1; // if removing divide the island\n grid[i][j] = 1; // restore cell\n }\n }\n }\n\n return 2;\n }\n};\n\n``` | 4 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | [Python] Tarjan's Algorithm + Articulation Point detection = at most 2 days of flipping 1s to 0s | python-tarjans-algorithm-articulation-po-s7m6 | Intuition\n Describe your first thoughts on how to solve this problem. \nThis is a haaaard problem if you don\'t know that we can take at most 2 days to separat | sinclaire | NORMAL | 2023-06-03T13:50:26.138836+00:00 | 2023-06-03T13:50:26.138884+00:00 | 202 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a haaaard problem if you don\'t know that we can take at most 2 days to separate a given island. We solve this using SCCs concept + articulation point detection.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use Tarjan\'s algorithm with articulation point detection. This enables us to calculate the number of islands (strongly connected components) in our grid. Moreover, we detect if we have an articulation point -> a node/point, if remove, will disconnect our SCC breaking it to separate SCCs\n2. Handle edge cases. If we have more than 1 SCCs, return 0. If we have an articulation point, return 1. Otherwise, check if we actually have islands in the grid. If no islands, return 0. If we have a single 1, return 1.\n3. Finally, if any of the above did not happen, return 2. Imagine a board full of 1. At the minimum, how many 1 should we erase to have two separate islands?\n\n# Complexity\n- Time complexity: $$O(m * n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m * n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n\n disc_time = [[-1 for _ in range(cols)] for _ in range(rows)]\n low_value = [[-1 for _ in range(cols)] for _ in range(rows)]\n parents = [[(-1, -1) for _ in range(cols)] for _ in range(rows)]\n is_ap = [[False for _ in range(cols)] for _ in range(rows)]\n dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\n time = 0\n has_ap = False\n def dfs(i, j):\n if grid[i][j] == 0:\n return\n nonlocal time\n nonlocal has_ap\n disc_time[i][j] = time\n low_value[i][j] = time\n time += 1\n\n child = 0\n for di, dj in dirs:\n ni, nj = i + di, j + dj\n if not (0 <= ni < rows) or not (0 <= nj < cols):\n continue\n if grid[ni][nj] != 1:\n continue\n\n if disc_time[ni][nj] == -1: # not visited\n child += 1\n parents[ni][nj] = (i, j)\n dfs(ni, nj)\n low_value[i][j] = min(low_value[i][j], low_value[ni][nj])\n\n if parents[i][j] == (-1, -1) and child > 1:\n is_ap[i][j] = True\n has_ap = True\n\n if parents[i][j] != (-1, -1) and low_value[ni][nj] >= disc_time[i][j]:\n is_ap[i][j] = True\n has_ap = True\n elif (ni, nj) != parents[i][j]:\n low_value[i][j] = min(low_value[i][j], disc_time[ni][nj])\n\n sccs = 0\n num_ones = 0\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n num_ones += 1\n if disc_time[i][j] == -1 and grid[i][j] == 1:\n dfs(i, j)\n sccs += 1\n\n\n if sccs > 1:\n return 0\n elif has_ap:\n return 1\n else:\n if num_ones == 1:\n return 1\n elif num_ones == 0:\n return 0\n return 2\n\n\n``` | 4 | 0 | ['Python3'] | 2 |
minimum-number-of-days-to-disconnect-island | [C++] 2 solutions, clean code, and detailed explanation | c-2-solutions-clean-code-and-detailed-ex-xg9f | The idea:\nFirst thing to notice is that we need atmost two days to disconnect an island. The intuition is that since diagonal does not count as a connection, g | haoran_xu | NORMAL | 2021-07-15T19:31:25.594185+00:00 | 2021-07-15T19:32:00.175049+00:00 | 315 | false | The idea:\nFirst thing to notice is that we need atmost two days to disconnect an island. The intuition is that since diagonal does not count as a connection, given a corner of the island, we can disconnect two of its connections (in fact it only has two connections) to seperate it. Notice that we can do this to any corner of an island.\n\nThe intuitive idea is to simply brute force our way through this question. Using a simple dfs, we can count the number of islands. If that number is larger than 1 we know that the island is disconnected. Therefore, let us count the number of island first without doing anything, if the grid is already disconnected, return 0. If the grid is not, we will remove every `1` in the grid and count the number of islands. If that number increase after 1 removal, we know that we can remove only 1 piece. Therefore, we can return 1. However, if removing any `1` won\'t give us a disconnected grid, we can safely return `2`.\n\nThis idea should be alot clearer once you see the implementation:\n```\nclass Solution {\n \n int n;\n int m;\n \n vector<vector<int>> offset{{-1,0},{1,0},{0,-1},{0,1}};\n \n \n void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int i, int j) {\n if(i < 0 || i >= n || j < 0 || j >= m || visited[i][j] || grid[i][j] == 0) return;\n \n visited[i][j] = true;\n for(int k = 0; k < 4; k++) {\n dfs(grid, visited, i + offset[k][0], j + offset[k][1]);\n }\n }\n \n bool one_islands(vector<vector<int>>& grid) {\n vector<vector<bool>> visited(n, vector<bool>(m, false));\n bool found = false;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] != 0 && !visited[i][j]) {\n if(!found) {\n found = true;\n dfs(grid, visited, i, j);\n }\n else return false;\n }\n }\n }\n \n return true && found;\n }\n \npublic:\n int minDays(vector<vector<int>>& grid) {\n n = grid.size();\n m = grid[0].size();\n \n bool test = one_islands(grid);\n if(!test) return 0;\n \n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] == 1) {\n grid[i][j] = 0;\n bool yes = one_islands(grid);\n if(!yes) return 1;\n grid[i][j] = 1;\n }\n }\n }\n \n return 2;\n }\n};\n```\nCouple of implementation details to address. First, notice that `one_islands` method return `true && found`. This is to account for cases where there is a single `1` in the entire grid. When that happens, we want to make sure that an empty grid is counted as disconnected. Counting the number of islands takes `O(n * m)` worst case we need to count it `n * m` times (a full grid of `1`). Therefore, the time complexity is `O((nm)^2)`, space complexity is `O(nm)` (`visited` array and call stack)\n\nThe second idea(Tarjan/Articulation point):\nSo time complexity of `O((nm)^2)` is not exactly thrilling. Is there a way we can improve this?\n\nThink of the grid as an undirected graph. If there is a way for us to remove 1 vertex to disconnect the graph, then we can safely return 1. This "critical" vertex is the `Articulation point`. As it turns out, this is a well known problem in finding vulnerabilities in networks and we can use Tarjan\'s Algorithm to solve this question. \n\nShort introduction to Tarjan\'s algorithm. Tarjan\'s algorithm is a single pass DFS algorithm that can find all strongly connected components. Tarjan mainly work by keeping track of the highest ancestor a vertex can reach in the DFS tree. This value is often kept within the array `low`. To do this we also need to keep track of the array `disc` which records the discovery time of each vertex. The array `parent` is also important for reasons we will discuss later, but it keeps track of the parent of a vertex in the DFS tree.\n\nHow can we use Tarjan to find the articultion point? Well, suppose we are on vertex `u` and we are process one of our children vertex `v`. After we recursived called on it if `low[v] <= disc[u]` it means that there is a path from `v` to a vertex above `u` in the DFS tree, confirming that `u` cannot be the articualtion point (we can reach `v` from that vertex above `u` by reversing the back edge, remember that this is a undirected graph). If `low[v] > disc[u]`, this means that `u` is a "choke point" for `v`, making `u` an articulation point. Similary, if `u` is the root of the DFS tree, if it has more than 2 children, it must be an articulation point too. \n\nIf you are confused, don\'t worry, Tarjan\'s algorithm is not friendly to people who don\'t understand them fully. I recommend goolging it and watching a few tutorials explaining Tarjan\'s. In addition, you can try this simmilar question in finding "bridge" of a network https://leetcode.com/problems/critical-connections-in-a-network/. Anyways, here is the implementation:\n```\nclass Solution {\n \n int n;\n int m;\n \n int time = 0;\n vector<vector<int>> offset{{-1,0},{1,0},{0,-1},{0,1}};\n \n bool ap(vector<vector<int>>& grid, vector<vector<bool>>& visited, vector<vector<int>>& low,\n vector<vector<int>>& disc, vector<vector<int>>& parent, int i, int j, bool is_parent) {\n int children = 0;\n visited[i][j] = true;\n \n disc[i][j] = low[i][j] = ++time;\n \n for(int k = 0; k < 4; k++) {\n int ci = i + offset[k][0];\n int cj = j + offset[k][1];\n \n if(ci < 0 || ci >= n || cj < 0 || cj >= m || grid[ci][cj] == 0) continue;\n \n if(!visited[ci][cj]) {\n children++;\n parent[ci][cj] = i * m + j;\n bool terminate = ap(grid, visited, low, disc, parent, ci, cj, false);\n if(terminate) return true;\n \n low[i][j] = min(low[i][j], low[ci][cj]);\n \n if(is_parent && children > 1) return true;\n \n if(!is_parent && low[ci][cj] >= disc[i][j]) return true;\n } else if (ci != parent[i][j] / m || cj != parent[i][j] % m) {\n low[i][j] = min(low[i][j], disc[ci][cj]);\n }\n }\n return false;\n }\n \n void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int i, int j) {\n if(i < 0 || i >= n || j < 0 || j >= m || visited[i][j] || grid[i][j] == 0) return;\n \n visited[i][j] = true;\n for(int k = 0; k < 4; k++) {\n dfs(grid, visited, i + offset[k][0], j + offset[k][1]);\n }\n }\n \n bool one_islands(vector<vector<int>>& grid) {\n vector<vector<bool>> visited(n, vector<bool>(m, false));\n bool found = false;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] != 0 && !visited[i][j]) {\n if(!found) {\n found = true;\n dfs(grid, visited, i, j);\n }\n else return false;\n }\n }\n }\n \n return true;\n }\n \npublic:\n int minDays(vector<vector<int>>& grid) {\n n = grid.size();\n m = grid[0].size();\n \n bool test = one_islands(grid);\n if(!test) return 0;\n \n vector<vector<bool>> visited(n, vector<bool>(m, false));\n vector<vector<int>> low(n, vector<int>(m, 0));\n vector<vector<int>> disc(n, vector<int>(m, 0));\n vector<vector<int>> parent(n, vector<int>(m, 0));\n \n int start_i = 0;\n int start_j = 0;\n for(; start_i < n; start_i++) {\n for(start_j = 0; start_j < m; start_j++) {\n if(grid[start_i][start_j] != 0) goto OUT;\n }\n }\n \n OUT:\n \n test = ap(grid, visited, low, disc, parent, start_i, start_j, true);\n if(test || time == 1) return 1;\n \n return 2;\n }\n};\n```\nNotice that we have to check `ci != parent[i][j] / m || cj != parent[i][j] % m` to make sure that we don\'t use an edge twice. Tarjan has the time complexity of `O(nm)`, therefore the entire algorithm has the time complexity of `O(nm)`. The space complexity is also `O(nm)` but with a lot more hidden constants. | 4 | 0 | [] | 0 |
minimum-number-of-days-to-disconnect-island | No Graphs Beats 100% CPP SOLUTION EASY AND INTUTIVE APPROACH | no-graphs-beats-100-cpp-solution-easy-an-lf7l | Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve this problem, we need to identify the minimum number of days (or steps) requir | Iheretocode | NORMAL | 2024-08-11T05:18:00.691095+00:00 | 2024-08-11T10:41:59.543575+00:00 | 41 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem, we need to identify the minimum number of days (or steps) required to separate the grid into two or more disconnected components or to remove all the land cells entirely.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# Step 1: Counting the Initial Components\n- First, we need to count the number of connected components in the grid initially. A connected component is a group of adjacent land cells (1s) connected in the four cardinal directions.\n- If the number of components is already more than 1, or if there are no components (no land cells), the grid is already disconnected, so we return 0.\n# Step 2: Checking for Disconnection with One Cell Removal\n- If the initial grid has exactly one connected component, we check whether removing any single land cell disconnects the grid.\n- We iterate through all the land cells, temporarily remove one cell, and count the number of connected components again.\n- If removing one cell increases the number of components, the grid can be disconnected in just one day, so we return 1.\n# Step 3: Returning the Result\nIf no single cell removal disconnects the grid, then the minimum number of days required must be 2, because removing any two adjacent cells will surely disconnect the grid.\n# Complexity\n- Time complexity: \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n X m)$$\nn=rows\nm=cols\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n$$O(1)$$-we did not take any extra storage \n# Code\n```\n#This code make your code run faster by turning off the various unnecessory compilation steps\nauto init = [](){\n cin.tie(NULL);\n cout.tie(NULL);\n ios_base::sync_with_stdio(false);\n return 0;\n}();\n\nclass Solution {\npublic:\n // Function to perform a Depth-First Search (DFS) to mark connected land cells\n void search(vector<vector<int>> &matrix, int i, int j) {\n // Boundary and base condition check\n if(i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() || matrix[i][j] == 0) {\n return;\n }\n \n // Mark the cell as visited\n matrix[i][j] = 0;\n \n // Recursively search all four directions\n search(matrix, i + 1, j);\n search(matrix, i, j - 1);\n search(matrix, i, j + 1);\n search(matrix, i - 1, j);\n }\n\n // Function to count the number of connected components in the grid\n int countComponents(vector<vector<int>> grid) {\n int n = grid.size();\n int m = grid[0].size();\n int initial = 0;\n\n // Iterate through each cell in the grid\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n // If a land cell (1) is found, perform DFS and increment the component count\n if(grid[i][j] == 1) {\n search(grid, i, j);\n initial++;\n }\n }\n }\n return initial;\n }\n\n // Main function to determine the minimum number of days to disconnect the grid\n int minDays(vector<vector<int>>& grid) {\n // Count initial components\n int initial = countComponents(grid);\n if(initial > 1 || initial == 0) {\n return 0; // Already disconnected\n } \n\n int n = grid.size();\n int m = grid[0].size();\n\n // Check if removing one land cell disconnects the grid\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] == 1) {\n grid[i][j] = 0; // Temporarily remove the land cell\n int newCount = countComponents(grid);\n if(newCount != initial) {\n return 1; // Grid is disconnected with one cell removal\n }\n grid[i][j] = 1; // Restore the land cell\n }\n }\n }\n\n // Otherwise, it requires two days to disconnect the grid\n return 2;\n }\n};\n\n```\n\n# Please Upvote | 3 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | C++ | Minimum Number of Days to Disconnect Island | 62ms | c-minimum-number-of-days-to-disconnect-i-7jiz | Intuition\nTo determine the minimum number of days required to disconnect a single island in a grid, we need to explore how the grid can be split into multiple | user4612MW | NORMAL | 2024-08-11T03:35:12.783380+00:00 | 2024-08-11T03:38:14.531197+00:00 | 20 | false | # Intuition\nTo determine the minimum number of days required to disconnect a single island in a grid, we need to explore how the grid can be split into multiple islands. Each day, we can change one land cell to water, and our goal is to find the minimum number of such changes needed to confirm that the grid is disconnected.\n\n# Approach\nTo solve the problem, first check if the grid is already disconnected by using a depth-first search (DFS) to count the number of islands. If there are zero islands, return 0. If the grid is connected, iterate through each land cell, changing it to water, and check if this action disconnects the grid; if so, return 1. If changing a single cell is insufficient, test all pairs of land cells to see if removing any two cells results in disconnection, and return 2 if successful.\n\n# Complexity\n- **Time complexity** $$O(m \\times n \\times (m \\times n))$$, where $$m$$ and $$n$$ are the dimensions of the grid. This accounts for checking connectivity after changing each cell and pairs of cells.\n- **Space complexity** $$O(m \\times n)$$, for the visited matrix used in DFS.\n\n# Code\n```\nclass Solution {\npublic:\n int minDays(vector<vector<int>>& grid) {\n int rows = grid.size(), cols = grid[0].size();\n auto isConnected = [&](vector<vector<int>>& g) -> bool {\n vector<vector<int>> vis(rows, vector<int>(cols));\n int islands{0};\n auto dfs = [&](int r, int c, auto&& dfs_ref) -> void {\n if (r < 0 || r >= rows || c < 0 || c >= cols || g[r][c] == 0 || vis[r][c]) return;\n vis[r][c] = 1;\n dfs_ref(r + 1, c, dfs_ref); dfs_ref(r - 1, c, dfs_ref);\n dfs_ref(r, c + 1, dfs_ref); dfs_ref(r, c - 1, dfs_ref);\n };\n for (int r{0}; r < rows && islands < 2; ++r)\n for (int c{0}; c < cols && islands < 2; ++c)\n if (g[r][c] == 1 && !vis[r][c]) {\n dfs(r, c, dfs);\n ++islands;\n }\n return islands == 1;\n };\n if (!isConnected(grid)) return 0;\n for (int r{0}; r < rows; ++r) {\n for (int c{0}; c < cols; ++c) {\n if (grid[r][c] == 1) {\n grid[r][c] = 0;\n if (!isConnected(grid)) return 1;\n grid[r][c] = 1;\n }\n }\n }\n return 2;\n }\n};\n\n```\n## **If you found this solution helpful, please upvote! \uD83D\uDE0A** | 3 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy to understand ✅ Python, C# 🔥 | Great runtime ✨ | easy-to-understand-python-c-great-runtim-e79o | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires finding the minimum number of days needed to disconnect a land mas | kotto | NORMAL | 2024-08-11T00:10:55.852950+00:00 | 2024-08-11T00:10:55.852968+00:00 | 632 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the minimum number of days needed to disconnect a land mass in a grid. My initial thought is to explore whether the grid is already disconnected, and if not, determine how quickly it can be split into separate land masses by removing cells. The key lies in understanding the concept of connected components and simulating the removal of land cells to observe their effect on connectivity.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\u2705 **Initial Check for Disconnection**\nThe first step is to determine if the grid is already disconnected. This can be done by counting the number of connected land components. If there is more than one component or no land at all, the grid is already disconnected, and the answer is 0 days.\n\n\u2705 **Simulate Cell Removals** \nIf the grid is initially connected, the next step is to simulate the removal of each land cell, one by one. After each removal, we check if the grid becomes disconnected. If removing a single cell causes the land to disconnect, it means it takes `1` day to achieve the disconnection.\n\n\u2705 **Worst-Case Scenario**\nIf removing one land cell does not disconnect the island, it indicates that the grid is more resilient and requires at least `2` days for complete disconnection. This happens when the island remains connected despite the removal of a single land cell, implying that further cell removals are necessary.\n\n\u2705 **Result** \nThe solution is designed to return `0`, `1`, or `2` days based on whether the grid is already disconnected, can be disconnected by removing one cell, or needs additional removals to achieve disconnection. This approach effectively and efficiently solves the problem by considering all possible scenarios.\n\n# Code\n**C#**\n```\npublic class Solution {\n // Arrays for direction vectors: up, down, left, right\n private int[] xDir = {0, 0, -1, 1};\n private int[] yDir = {-1, 1, 0, 0};\n\n // Checks if the cell (i, j) is within bounds, unvisited, and is land (1)\n public bool IsSafe(int[][] grid, int i, int j, bool[][] visited)\n {\n return (i >= 0 && j >= 0 && i < grid.Length && j < grid[0].Length && !visited[i][j] && grid[i][j] == 1);\n }\n\n // Recursive DFS function to mark all connected parts of land as visited\n public void IslandCount(int[][] grid, int i, int j, bool[][] visited)\n {\n // Mark the current cell as visited\n visited[i][j] = true;\n \n // Traverse all four possible directions\n for (int k = 0; k < 4; k++)\n {\n int newRow = i + xDir[k];\n int newCol = j + yDir[k];\n // If the new cell is safe, continue the DFS\n if (IsSafe(grid, newRow, newCol, visited))\n {\n IslandCount(grid, newRow, newCol, visited);\n }\n }\n }\n\n // Function to count the number of connected land components in the grid\n public int CountLand(int[][] grid, bool[][] visited)\n {\n int count = 0;\n // Iterate through all cells in the grid\n for (int i = 0; i < grid.Length; i++)\n {\n for (int j = 0; j < grid[0].Length; j++)\n {\n // If we find unvisited land, start a new DFS\n if (grid[i][j] == 1 && !visited[i][j])\n {\n IslandCount(grid, i, j, visited);\n count++;\n }\n }\n }\n return count;\n }\n\n // Main function to solve the problem\n public int MinDays(int[][] grid)\n {\n int rows = grid.Length;\n int cols = grid[0].Length;\n \n // Initialize a visited array to track visited cells\n bool[][] visited = new bool[rows][];\n for (int i = 0; i < rows; i++)\n {\n visited[i] = new bool[cols];\n }\n\n // Check how many connected land components exist initially\n int count = CountLand(grid, visited);\n \n // If more than one island or no land, no days are needed\n if (count > 1 || count == 0) return 0;\n\n // Simulate the removal of each land cell and check if it splits the island\n for (int i = 0; i < rows; i++)\n {\n for (int j = 0; j < cols; j++)\n {\n if (grid[i][j] == 1)\n {\n // Temporarily remove the land cell\n grid[i][j] = 0;\n \n // Check the number of components after removal\n bool[][] mat = new bool[rows][];\n for (int k = 0; k < rows; k++)\n {\n mat[k] = new bool[cols];\n }\n\n int count2 = CountLand(grid, mat);\n \n // Restore the removed cell\n grid[i][j] = 1;\n \n // If the island is now split or there is no land, only one day is needed\n if (count2 > 1 || count2 == 0)\n {\n return 1; \n }\n }\n }\n }\n\n // If removing one cell does not split the island, two days are needed\n return 2;\n }\n}\n\n\n```\n\n**Python**\n\n```\nclass Solution:\n # Direction vectors for moving up, down, left, and right\n def __init__(self):\n self.xDir = [0, 0, -1, 1]\n self.yDir = [-1, 1, 0, 0]\n\n # Check if the cell (i, j) is within bounds, unvisited, and is land (1)\n def is_safe(self, grid, i, j, visited):\n return (0 <= i < len(grid) and 0 <= j < len(grid[0]) and not visited[i][j] and grid[i][j] == 1)\n\n # Recursive DFS function to mark all connected parts of land as visited\n def island_count(self, grid, i, j, visited):\n # Mark the current cell as visited\n visited[i][j] = True\n \n # Traverse all four possible directions\n for k in range(4):\n newRow = i + self.xDir[k]\n newCol = j + self.yDir[k]\n # If the new cell is safe, continue the DFS\n if self.is_safe(grid, newRow, newCol, visited):\n self.island_count(grid, newRow, newCol, visited)\n\n # Function to count the number of connected land components in the grid\n def count_land(self, grid, visited):\n count = 0\n # Iterate through all cells in the grid\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n # If we find unvisited land, start a new DFS\n if grid[i][j] == 1 and not visited[i][j]:\n self.island_count(grid, i, j, visited)\n count += 1\n return count\n\n # Main function to solve the problem\n def minDays(self, grid):\n rows = len(grid)\n cols = len(grid[0])\n \n # Initialize a visited array to track visited cells\n visited = [[False] * cols for _ in range(rows)]\n\n # Check how many connected land components exist initially\n count = self.count_land(grid, visited)\n \n # If more than one island or no land, no days are needed\n if count > 1 or count == 0:\n return 0\n\n # Simulate the removal of each land cell and check if it splits the island\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n # Temporarily remove the land cell\n grid[i][j] = 0\n \n # Check the number of components after removal\n mat = [[False] * cols for _ in range(rows)]\n count2 = self.count_land(grid, mat)\n \n # Restore the removed cell\n grid[i][j] = 1\n \n # If the island is now split or there is no land, only one day is needed\n if count2 > 1 or count2 == 0:\n return 1 \n\n # If removing one cell does not split the island, two days are needed\n return 2\n\n``` | 3 | 0 | ['Depth-First Search', 'Matrix', 'Python3', 'C#'] | 3 |
minimum-number-of-days-to-disconnect-island | C++ DFS solution | c-dfs-solution-by-sachin_kumar_sharma-p3bl | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Sachin_Kumar_Sharma | NORMAL | 2024-04-18T03:56:25.886862+00:00 | 2024-04-18T03:56:25.886885+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O((m*n)^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nvector<int> dx={1,-1,0,0};\nvector<int> dy={0,0,-1,1};\nvoid dfs(int currI,int currJ,vector<vector<int>> &grid,vector<vector<bool>> &vis){\n if(currI<0 || currJ<0 || currI>=grid.size() || currJ>=grid[0].size() || vis[currI][currJ]) return;\n vis[currI][currJ]=true;\n\n// dfs(currI-1,currJ,grid,vis);\n// dfs(currI,currJ-1,grid,vis);\n// dfs(currI+1,currJ,grid,vis);\n// dfs(currI,currJ+1,grid,vis);\n\nfor(int i=0;i<4;i++){\n int nx=currI+dx[i];\n int ny=currJ+dy[i];\n\n if(nx>=0 && ny>=0 && nx<grid.size() && ny<grid[0].size() && !vis[nx][ny]\n && grid[nx][ny]) dfs(nx,ny,grid,vis);\n}\n\n}\nint countIslands(vector<vector<int>> &grid){\n int cnt=0,m=grid.size(),n=grid[0].size(),i,j;\n vector<vector<bool>> vis(m,vector<bool>(n,false));\n\n for(i=0;i<m;i++){\n for(j=0;j<n;j++){\n if(!vis[i][j] && grid[i][j]){\n dfs(i,j,grid,vis);\n cnt++;\n }\n }\n }\n\n return cnt;\n}\n int minDays(vector<vector<int>>& grid) {\n int i,j,m=grid.size(),n=grid[0].size(),cntIsland=0;\n cntIsland=countIslands(grid);\n\n if(cntIsland>1 || cntIsland==0) return 0;\n else{\n for(i=0;i<m;i++){\n for(j=0;j<n;j++){\n if(grid[i][j]){\n grid[i][j]=0;\n cntIsland=countIslands(grid);\n grid[i][j]=1;\n\n if(cntIsland>1 || cntIsland==0) return 1;\n }\n }\n }\n }\n return 2;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy BFS Solution || C++ || Number of Island | easy-bfs-solution-c-number-of-island-by-wxvj7 | \nclass Solution {\nprivate:\n int totalLand(vector<vector<int>>& grid)\n {\n int n = grid.size() , m = grid[0].size();\n vector<vector<int> | RIOLOG | NORMAL | 2023-10-26T15:31:46.201594+00:00 | 2023-10-26T15:31:46.201626+00:00 | 712 | false | ```\nclass Solution {\nprivate:\n int totalLand(vector<vector<int>>& grid)\n {\n int n = grid.size() , m = grid[0].size();\n vector<vector<int>>vis(n,vector<int>(m,0));\n int count = 0;\n\n for (int i=0;i<n;i++)\n {\n for (int j=0;j<m;j++)\n {\n if (grid[i][j] == 1 and !vis[i][j])\n {\n queue<pair<int,int>>q;\n vis[i][j] = 1;\n q.push({i,j});\n count += 1;\n \n while(!q.empty())\n {\n int row = q.front().first;\n int col = q.front().second;\n q.pop();\n\n int delrow [] = {-1,0,+1,0};\n int delcol [] = {0,1,0,-1};\n for (int i=0;i<4;i++)\n {\n int nrow = row + delrow[i];\n int ncol = col + delcol[i];\n if (nrow >=0 and nrow < grid.size() and ncol >= 0 and ncol < grid[0].size() and !vis[nrow][ncol] and grid[nrow][ncol] == 1)\n {\n q.push({nrow,ncol});\n vis[nrow][ncol] = 1;\n }\n }\n }\n }\n }\n }\n \n return count;\n }\npublic:\n int minDays(vector<vector<int>>& grid) \n {\n int initialLand = totalLand(grid);\n if (initialLand == 0 or initialLand >= 2) return 0;\n \n for (int i=0;i<grid.size();i++)\n {\n for (int j=0;j<grid[0].size();j++)\n {\n if (grid[i][j] == 1)\n {\n grid[i][j] = 0;\n int newLand = totalLand(grid);\n if (newLand != 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n \n return 2;\n }\n};\n``` | 3 | 0 | ['Breadth-First Search', 'C++'] | 1 |
minimum-number-of-days-to-disconnect-island | C++| BFS | islands-problems | Easy-to-understand | c-bfs-islands-problems-easy-to-understan-638j | Intuition\n Describe your first thoughts on how to solve this problem. \nAll the posted solutions are using the similar basic flow:\n\n- If there is no island o | sko_1 | NORMAL | 2022-12-14T07:15:42.753048+00:00 | 2022-12-14T07:15:42.753093+00:00 | 741 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAll the posted solutions are using the similar basic flow:\n\n- If there is no island or more than 1 island, return 0;\n- If there is only one land, return 1;\n- If any single cell could serve as the cut point ( divide 1 island into 2 islands), return 1;\n- Otherwise, return 2 \n\n# Approach\nUsing BFS to find number of island after replacing land to water\n\n<!-- Time Complexity: O((m*n)^2) -->\n# Code\n```\nclass Solution {\npublic:\n vector<int>dx = {1, 0, -1, 0};\n vector<int>dy = {0, 1, 0, -1};\n \n int number_of_island(vector<vector<int>>&grid, int row, int col)\n {\n vector<vector<int>>vis(row, vector<int>(col, 0));\n int count = 0; //number of island\n queue<pair<int, int>>q;\n for(int i=0;i<row;i++)\n {\n for(int j=0;j<col;j++)\n {\n if(grid[i][j]==1 && vis[i][j] == 0)\n {\n vis[i][j] = 1;\n q.push({i,j});\n count++;\n while(q.empty()==false)\n {\n int sz = q.size();\n while(sz--)\n {\n auto curr = q.front(); q.pop();\n int f = curr.first;\n int s = curr.second;\n for(int k=0;k<4;k++)\n {\n int u = f + dx[k];\n int v = s + dy[k];\n if(u < row && u >= 0 && v < col && v >= 0 && grid[u][v] == 1 && vis[u][v] == 0 )\n {\n q.push({u, v});\n vis[u][v] =1 ;\n }\n }\n }\n }\n }\n }\n }\n return count;\n }\n int minDays(vector<vector<int>>& grid) {\n int row = grid.size();\n int col = grid[0].size();\n int count = number_of_island(grid, row, col); // initial number of island\n \n if (count > 1 or count == 0)\n {\n return 0;\n }\n for(int i=0;i<row;i++)\n {\n for(int j=0;j<col;j++)\n {\n int islands = 0;\n if(grid[i][j]==1)\n {\n int temp=grid[i][j];\n grid[i][j]=0; // change land to water\n \n islands=number_of_island(grid,row,col);\n if(islands!=1)\n return 1; \n \n grid[i][j]=temp; // replace our changed water cell to land \n }\n }\n }\n return 2;\n }\n};\n``` | 3 | 0 | ['C++'] | 1 |
minimum-number-of-days-to-disconnect-island | C++ | islands-problems | medium-hard | c-islands-problems-medium-hard-by-chikzz-3q08 | PLEASE UPVOTE IF YOU FIND MY SOLUTION HELPFUL\n\n\nclass Solution {\n int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};\n bool vis[31][31];\n int noOfIslands( | chikzz | NORMAL | 2022-03-30T05:35:34.216282+00:00 | 2022-03-30T05:35:34.216307+00:00 | 534 | false | **PLEASE UPVOTE IF YOU FIND MY SOLUTION HELPFUL**\n\n```\nclass Solution {\n int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};\n bool vis[31][31];\n int noOfIslands(vector<vector<int>>& grid,int &n,int &m)\n {\n int islands=0;\n memset(vis,0,sizeof(vis));\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(grid[i][j])\n {\n islands++;\n dfs(grid,i,j,n,m);\n }\n }\n }\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n grid[i][j]=vis[i][j]?1:0;\n }\n \n return islands;\n }\n void dfs(vector<vector<int>>& grid,int i,int j,int &n,int &m)\n {\n if(i<0||j<0||i>=n||j>=m||!grid[i][j])return;\n vis[i][j]=1;\n grid[i][j]=0;\n \n for(int k=0;k<4;k++)\n {\n int ni=i+dir[k][0];\n int nj=j+dir[k][1];\n \n dfs(grid,ni,nj,n,m);\n }\n }\npublic:\n int minDays(vector<vector<int>>& grid) \n {\n //we can disconnect the island into 2 from the corner by at most 2 changes\n //00000 00000\n //01110 01010\n //01110---->00110\n //01110 01110\n //00000 00000\n \n //so basically in the worst case we need 2 steps-->ans can be 0,1,2\n \n int n=grid.size(),m=grid[0].size();\n \n //edge cases\n if(n==1&&m==1)\n return grid[0][0];\n \n if(n*m==2)\n {\n int countOnes=0;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {if(grid[i][j]==1)countOnes++;}\n }\n return countOnes;\n }\n \n int initialIslands=noOfIslands(grid,n,m);\n\n //made mistake in the checking condition dumbo :\'( islands must not be one that is it\n //zero islands are considered valid cases\n \n if(initialIslands!=1)return 0;\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n int islands=0;\n if(grid[i][j])\n {\n int temp=grid[i][j];\n grid[i][j]=0;\n \n islands=noOfIslands(grid,n,m);\n if(islands!=1)return 1; \n \n grid[i][j]=temp;\n }\n }\n }\n \n return 2;\n }\n};\n\n\n``` | 3 | 0 | ['Depth-First Search', 'Recursion'] | 1 |
minimum-number-of-days-to-disconnect-island | C++, Articulation Point O(m + n) | c-articulation-point-om-n-by-level7-hnwc | Guys, Comment me if you have any questions, Approach is pretty similar to AP but we need to consider some corner cases as well, \nCase 1 : there is only one isl | level7 | NORMAL | 2021-08-09T22:12:20.994331+00:00 | 2022-01-06T20:42:21.610991+00:00 | 725 | false | Guys, Comment me if you have any questions, Approach is pretty similar to AP but we need to consider some corner cases as well, \nCase 1 : there is only one island and one land return 1\nCase 2 : if no of islands are more than one -> in this case we need to return 0;\nCase 3: there is only one island and two lands return 2;\nCase 4: if there is an AP present return 1;\nCase 5: No Island return 0;\nAll other cases: return 2;\n\n\n```\nclass Solution {\n void dfs(list<int>* adj, vector<bool>& visited, vector<int>& discTime, vector<int>& lowTime, int& ap, int parent, int u){\n visited[u] = true;\n static int time = 0;\n discTime[u] = lowTime[u] = ++time;\n \n list<int>:: iterator itr;\n \n for(itr = adj[u].begin(); itr != adj[u].end(); itr++ ){\n int v = *itr;\n \n if(!visited[v]){\n dfs(adj, visited, discTime, lowTime, ap, u, v);\n lowTime[u] = min(lowTime[u], lowTime[v]);\n \n if(lowTime[v] > discTime[u]){\n ap++;\n }\n }\n else if(parent != v){\n lowTime[u] = min(lowTime[u], discTime[v]);\n }\n }\n }\npublic:\n int minDays(vector<vector<int>>& grid) {\n if(grid.size() == 0) return 0;\n \n int m = grid.size();\n int n = grid[0].size();\n int size = m*n;\n int count = 0;\n vector<int> disc(size, 0);\n vector<int> low(size, 0);\n vector<bool> visited(size, false);\n int ap = 0;\n list<int> adj[size];\n int ones = size;\n \n for(int i = 0; i < m; i++ ){\n for(int j = 0; j < n; j++ ){\n if(grid[i][j]){\n if(i+1 < m && grid[i+1][j]){\n adj[i*n + j].push_back((i+1)*n + j);\n adj[(i+1)*n + j].push_back(i*n + j);\n }\n if(i-1 >= 0 && grid[i-1][j]){\n adj[i*n + j].push_back((i-1)*n + j);\n adj[(i-1)*n + j].push_back(i*n + j);\n }\n if(j+1 < n && grid[i][j+1]){\n adj[i*n + j].push_back(i*n + (j+1));\n adj[(i*n + (j+1))].push_back(i*n + j);\n }\n if(j-1 >= 0 && grid[i][j-1]){\n adj[i*n + j].push_back(i*n + (j-1));\n adj[(i*n + (j-1))].push_back(i*n + j);\n } \n }\n else{\n visited[i*n + j] = true;\n ones--;\n }\n }\n }\n \n // Case 1 : there is only one island and one land\n if(ones == 1) return 1;\n \n for(int i = 0; i < size; i++ ){\n if(!visited[i]){\n dfs(adj, visited, disc, low, ap, -1, i);\n count++;\n }\n }\n \n \n // Case 2: island are more than 1 \n if(count > 1) return 0;\n \n // Case 3: there is only one island and two lands\n if(ones == 2) return 2;\n \n // Case 4: if there is an AP present\n if(ap) return 1;\n \n\t\t// Case 5: No Island\n if(count == 0) return 0;\n \n // All other cases \n return 2;\n \n \n }\n};\n``` | 3 | 0 | ['C'] | 2 |
minimum-number-of-days-to-disconnect-island | C++ DFS 1/4 Positive | c-dfs-14-positive-by-votrubac-vrtc | The answer is:\n1. Zero if there is no islands or more than one island.\n2. One when there is a single piece of land that connects two or more semi-islands. \n3 | votrubac | NORMAL | 2020-09-01T01:48:01.181210+00:00 | 2020-09-01T01:58:59.187254+00:00 | 139 | false | The answer is:\n1. Zero if there is no islands or more than one island.\n2. One when there is a single piece of land that connects two or more semi-islands. \n3. Two otherwise.\n\nHow to tell if a land connects semi-islands? If it does not, doing DFS in one direction will explore the entire island. If it does, we need to do DFS in more directions.\n\nIn other words, if a land does not connect semi-islands, the result of DFS will be positive for only one direction.\n\n```cpp\nint fill(vector<vector<int>>& g, int i, int j, int col, bool top = false) {\n if (i < 0 || j < 0 || i >= g.size() || j >= g[i].size() || g[i][j] != col)\n return 0;\n g[i][j] = col + 1;\n int r = fill(g, i + 1, j, col), l = fill(g, i - 1, j, col);\n int d = fill(g, i, j + 1, col), u = fill(g, i, j - 1, col);\n if (top)\n return max({r, l, d, u}) == r + l + d + u ? 2 : 1;\n else \n return 1 + r + l + d + u;\n}\nint minDays(vector<vector<int>>& g) {\n int res = 0;\n for (auto i = 0; i < g.size(); ++i)\n for (auto j = 0; j < g[i].size(); ++j) {\n if (g[i][j]) {\n if (g[i][j] == 1 && res != 0)\n return 0;\n res = res == 1 ? 1 : fill(g, i, j, g[i][j], true);\n }\n }\n return res;\n}\n``` | 3 | 3 | [] | 0 |
minimum-number-of-days-to-disconnect-island | [JavaScript] Find the critical points and check O(MNK) (K: number of critical point) | javascript-find-the-critical-points-and-t29rk | The maximum answer could only be 2.\nEx:\n0111\n0111\n0111\n0000\n-->\n0111\n0011\n0101\n0000\n\nSince we know this rule. Now we have to do the following steps: | alanchanghsnu | NORMAL | 2020-08-30T04:02:23.381740+00:00 | 2020-08-30T04:12:54.952013+00:00 | 386 | false | The maximum answer could only be 2.\nEx:\n0111\n0111\n0111\n0000\n-->\n0111\n0011\n0101\n0000\n\nSince we know this rule. Now we have to do the following steps:\n1. Is it only one island?\n\tYes: Go next Step\n\tNo: return 0\n2. In the step 1, you can check which land connect 2 lands at most\n If connect 1 land, return 1\n\tIf connect 2 lands, it is critical point\n3. Check every case by converting critical point to 0\n\n```\nfunction markIsland(x, y, checked, grid, bridges = []) {\n let land = 0;\n const moves = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n checked[x][y] = true;\n let newi, newj;\n\n for (let move of moves) {\n let i = x + move[0],\n j = y + move[1];\n\n if (0 <= i && i < grid.length && 0 <= j && j < grid[0].length && grid[i][j] == 1) {\n land++;\n if (checked[i][j] == false)\n markIsland(i, j, checked, grid, bridges);\n if (land == 1) {\n newi = i;\n newj = j;\n }\n }\n }\n if (land == 2)\n bridges.push([x, y]);\n if (land == 1)\n bridges.push([newi, newj]);\n}\n\nfunction isOneIsland(grid, bridges) {\n const checked = [...Array(grid.length)].map(() => new Array(grid[0].length).fill(false));\n let islandCount = 0;\n \n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n if (!checked[i][j] && grid[i][j] == 1) {\n islandCount++;\n markIsland(i, j, checked, grid, bridges);\n }\n }\n }\n \n return islandCount;\n}\n\nvar minDays = function(grid) {\n const checked = [...Array(grid.length)].map(() => new Array(grid[0].length).fill(false));\n let bridges = [];\n let islandCount = isOneIsland(grid, bridges);\n if (islandCount !== 1)\n return 0;\n \n for (let [x, y] of bridges) {\n grid[x][y] = 0;\n if (isOneIsland(grid) !== 1) {\n return 1;\n }\n grid[x][y] = 1;\n }\n \n return 2;\n};\n | 3 | 0 | ['JavaScript'] | 1 |
minimum-number-of-days-to-disconnect-island | easy solution | easy-solution-by-paramdotcom-mwo1 | \n\n#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution\n{\npublic:\n void bfs(vector<vector<int>> &grid, int i, int j, int check)\n {\n | paramdotcom | NORMAL | 2024-08-11T17:04:40.627851+00:00 | 2024-08-11T17:04:40.627895+00:00 | 10 | false | \n```\n#include <bits/stdc++.h>\nusing namespace std;\n\nclass Solution\n{\npublic:\n void bfs(vector<vector<int>> &grid, int i, int j, int check)\n {\n if (i - 1 >= 0 && grid[i - 1][j] == check)\n {\n grid[i - 1][j] = check + 1;\n bfs(grid, i - 1, j, check);\n }\n if (j - 1 >= 0 && grid[i][j - 1] == check)\n {\n grid[i][j - 1] = check + 1;\n bfs(grid, i, j - 1, check);\n }\n if (i + 1 < grid.size() && grid[i + 1][j] == check)\n {\n grid[i + 1][j] = check + 1;\n bfs(grid, i + 1, j, check);\n }\n if (j + 1 < grid[0].size() && grid[i][j + 1] == check)\n {\n grid[i][j + 1] = check + 1;\n bfs(grid, i, j + 1, check);\n }\n }\n\n int countIslands(vector<vector<int>> grid, int batk)\n {\n int temp = 0;\n for (int i = 0; i < grid.size(); i++)\n {\n for (int j = 0; j < grid[0].size(); j++)\n {\n if (grid[i][j] == batk)\n {\n grid[i][j] = batk + 1;\n bfs(grid, i, j, batk);\n temp++;\n }\n }\n }\n return temp;\n }\n\n int minDays(vector<vector<int>> &grid)\n {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n int island = countIslands(grid, 1);\n if (island > 1 || island == 0)\n {\n return 0;\n }\n for (int i = 0; i < grid.size(); i++)\n {\n for (int j = 0; j < grid[0].size(); j++)\n {\n if (grid[i][j] == 1)\n {\n grid[i][j] = 0;\n int b = countIslands(grid, 1);\n if (b == 0 || b > 1)\n {\n return 1;\n }\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy for Beginner || Simple Approach || Full Explanation | easy-for-beginner-simple-approach-full-e-q9e7 | Approach\nHere\'s the approach:\n\nDepth-First Search (DFS): The dfs function is used to traverse the grid in a depth-first manner. It starts from a cell (i, j) | Rohan_k14 | NORMAL | 2024-08-11T13:34:19.718269+00:00 | 2024-08-11T13:34:19.718300+00:00 | 171 | false | # Approach\nHere\'s the approach:\n\nDepth-First Search (DFS): The dfs function is used to traverse the grid in a depth-first manner. It starts from a cell (i, j), and if the cell is within the grid boundaries, not visited before, and is land (grid[i][j] == 1), it marks it as visited and continues the search in all four directions (up, down, left, right).\n\nCounting Islands: The isLandCount function uses the dfs function to count the number of islands in the grid. It iterates over each cell in the grid, and if the cell is land and not visited before, it increments the count and starts a DFS from that cell.\n\nMinimum Days to Cut Off All Islands: The minDays function first checks if the number of islands is not 1. If it\'s not 1, it returns 0 because the islands are already disconnected. If it\'s 1, it iterates over each cell in the grid, and if the cell is land, it temporarily changes it to water (grid[i][j] = 0) and checks the number of islands. If the number of islands is not 1, it means that removing this cell disconnects the island, so it returns 1. If no such cell is found after checking all cells, it returns 2 because in the worst case, removing any two land cells will disconnect the island.\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited,int i, int j){\n int m = grid.size();\n int n = grid[0].size();\n\n if(i<0 || j<0 || i>=m || j>=n || grid[i][j]==0 || visited[i][j]){\n return;\n }\n\n visited[i][j] = true;\n\n dfs(grid, visited, i+1, j);\n dfs(grid, visited, i-1, j);\n\n dfs(grid, visited, i, j+1);\n dfs(grid, visited, i, j-1);\n }\n\n int isLandCount(vector<vector<int>>& grid){\n int count = 0;\n vector<vector<bool>> visited(grid.size(),vector<bool>(grid[0].size(),false));\n for(int i = 0; i<grid.size();i++){\n for(int j = 0; j<grid[0].size(); j++){\n if(grid[i][j] == 1 && !visited[i][j]){\n count++;\n dfs(grid,visited,i,j);\n }\n }\n }\n\n return count;\n }\n\n int minDays(vector<vector<int>>& grid) {\n if(isLandCount(grid)!=1) return 0;\n\n for(int i = 0; i<grid.size(); i++){\n for(int j = 0; j<grid[0].size(); j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n\n if(isLandCount(grid) != 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
minimum-number-of-days-to-disconnect-island | Easy Solution in C | easy-solution-in-c-by-tamilarasanmurugan-kjf5 | Intuition\nThe problem is about determining the minimum number of operations (days) needed to disconnect a grid by removing cells. The goal is to break the grid | TamilarasanMurugan | NORMAL | 2024-08-11T13:05:32.203190+00:00 | 2024-08-11T13:05:32.203216+00:00 | 15 | false | # Intuition\nThe problem is about determining the minimum number of operations (days) needed to disconnect a grid by removing cells. The goal is to break the grid into multiple islands by removing as few cells as possible.\n\n# Approach\n1.Initial Island Check: First, check if the grid is already disconnected. If it is (i.e., there is more than one island), return 0.\n2.Single Cell Removal: Try removing each cell in the grid one by one. After each removal, check if the grid becomes disconnected. If it does, return 1.\n3.Double Cell Removal: If removing a single cell doesn\u2019t disconnect the grid, try removing each possible pair of cells. Check if this leads to the grid being disconnected. If it does, return 2.\n4.Return 3: If removing one or two cells doesn\'t disconnect the grid, return 3 as the worst-case scenario where you may need to remove more cells.\n\n# Complexity\n- Time complexity:\n1.Counting islands: O(m\xD7n) for each DFS call.\n2.Single cell removal: O(m\xD7n) cells to check, and for each, counting islands is O(m\xD7n), so this step is O((m\xD7n)^2).\n3.Double cell removal: O((m\xD7n)^3) in the worst case, considering the nested loops.\n\n- Space complexity:\nThe space complexity is O(m\xD7n) for the visited array used in DFS.\n\n# Code\n```\n#define MAX_SIZE 100\n\nint dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n// Function to check if the given coordinates are within the grid boundaries\nint isValid(int x, int y, int m, int n) {\n return (x >= 0 && x < m && y >= 0 && y < n);\n}\n\n// Depth-first search to mark all cells in the same island\nvoid dfs(int** grid, int** visited, int x, int y, int m, int n) {\n visited[x][y] = 1;\n for (int i = 0; i < 4; i++) {\n int nx = x + dir[i][0];\n int ny = y + dir[i][1];\n if (isValid(nx, ny, m, n) && grid[nx][ny] == 1 && !visited[nx][ny]) {\n dfs(grid, visited, nx, ny, m, n);\n }\n }\n}\n\n// Function to count the number of islands in the grid\nint countIslands(int** grid, int m, int n) {\n int** visited = (int**)malloc(m * sizeof(int*));\n for (int i = 0; i < m; i++) {\n visited[i] = (int*)malloc(n * sizeof(int));\n memset(visited[i], 0, n * sizeof(int));\n }\n int count = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n count++;\n dfs(grid, visited, i, j, m, n);\n }\n }\n }\n for (int i = 0; i < m; i++) {\n free(visited[i]);\n }\n free(visited);\n return count;\n}\n\n// Main function to return the minimum number of days to disconnect the grid\nint minDays(int** grid, int gridSize, int* gridColSize) {\n int m = gridSize;\n int n = gridColSize[0];\n\n if (countIslands(grid, m, n) != 1) {\n return 0;\n }\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (countIslands(grid, m, n) != 1) {\n grid[i][j] = 1; // Restore the grid before returning\n return 1;\n }\n grid[i][j] = 1; // Restore the grid\n }\n }\n }\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n for (int k = 0; k < m; k++) {\n for (int l = 0; l < n; l++) {\n if (grid[k][l] == 1) {\n grid[k][l] = 0;\n if (countIslands(grid, m, n) != 1) {\n grid[k][l] = 1; // Restore the grid before returning\n grid[i][j] = 1; // Restore the grid before returning\n return 2;\n }\n grid[k][l] = 1; // Restore the grid\n }\n }\n }\n grid[i][j] = 1; // Restore the grid\n }\n }\n }\n\n return 3;\n}\n``` | 2 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'C', 'Matrix', 'Strongly Connected Component'] | 0 |
minimum-number-of-days-to-disconnect-island | DFS || C++ || Clean Code & Easy Solution | dfs-c-clean-code-easy-solution-by-zishan-5him | Code\n\nclass Solution {\npublic:\n int n, m;\n int vis[31][31];\n vector<pair<int, int> > dir = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};\n\n bool isVali | zishan_0point1 | NORMAL | 2024-08-11T09:09:42.989121+00:00 | 2024-08-11T09:09:42.989152+00:00 | 121 | false | # Code\n```\nclass Solution {\npublic:\n int n, m;\n int vis[31][31];\n vector<pair<int, int> > dir = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};\n\n bool isValid(int r, int c){\n return r >= 0 && r < n && c >= 0 && c < m;\n }\n void dfs(int x, int y, vector<vector<int>>& grid){\n vis[x][y] = 1;\n for(auto it: dir){\n int r = it.first + x, c = it.second + y;\n if(isValid(r, c) && !vis[r][c] && grid[r][c]) dfs(r, c, grid);\n }\n }\n\n int minDays(vector<vector<int>>& grid) {\n n = grid.size();\n m = grid[0].size();\n int island = 0;\n memset(vis, 0, sizeof(vis));\n\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n if(!vis[i][j] && grid[i][j]) dfs(i, j, grid), island++;\n }\n }\n if(island != 1) return 0;\n\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n \n if(grid[i][j]){\n grid[i][j] = 0;\n island = 0;\n memset(vis, 0, sizeof(vis));\n\n for(int k = 0; k < n; k++){\n for(int l = 0; l < m; l++){\n if(!vis[k][l] && grid[k][l]) dfs(k, l, grid), island++;\n }\n }\n grid[i][j] = 1;\n }\n if(island != 1) return 1;\n }\n }\n return 2;\n }\n};\n``` | 2 | 0 | ['Depth-First Search', 'Matrix', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy to understand ||BFS || Beats 70% || C++ | easy-to-understand-bfs-beats-70-c-by-har-apnv | Intuition\n Describe your first thoughts on how to solve this problem. \nThe bfs or dfs function is used to mark all connected land cells starting from a given | hardik-chauhan | NORMAL | 2024-08-11T07:19:15.627841+00:00 | 2024-08-11T07:19:15.627885+00:00 | 61 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe bfs or dfs function is used to mark all connected land cells starting from a given cell as visited. The isConnected function checks if all land cells are connected by using the bfs function. The minDays function first checks if the grid is already disconnected. If not, it tries removing each land cell one by one and checks if the grid becomes disconnected. If removing one cell disconnects the grid, it returns 1; otherwise, it returns 2, indicating that at least two cells need to be removed to disconnect the grid.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Define BFS Function**:\n - Create a `bfs` function to traverse the grid.\n - Use a queue to explore all connected land cells starting from a given cell.\n - Mark visited cells by setting their value to `-1`.\n\n2. **Check Grid Connectivity**:\n - Implement `isConnected` to verify if all land cells are connected.\n - Create a temporary copy of the grid.\n - Use `bfs` to mark all connected cells starting from the first land cell found.\n - If any land cell remains unvisited after BFS, return `false`.\n\n3. **Initial Connectivity Check**:\n - In `minDays`, first check if the grid is already disconnected using `isConnected`.\n - If the grid is disconnected, return `0`.\n\n4. **Single Cell Removal Check**:\n - Iterate through each cell in the grid.\n - For each land cell, temporarily set it to water (`0`).\n - Check if the grid becomes disconnected using `isConnected`.\n - If removing one cell disconnects the grid, return `1`.\n - Restore the cell to land (`1`) if it doesn\'t disconnect the grid.\n\n5. **Return Result**:\n - If no single cell removal disconnects the grid, return `2`.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n*m)^2$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n*m)$$\n# Code\n```\nclass Solution {\npublic:\n void bfs(int i, int j, vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n queue<pair<int, int>> q;\n q.push({i, j});\n grid[i][j] = -1; // Mark as visited\n while (!q.empty()) {\n pair<int, int> current = q.front();\n int row = current.first;\n int col = current.second;\n q.pop(); \n if (row - 1 >= 0 && grid[row - 1][col] == 1) { // Move up\n grid[row - 1][col] = -1;\n q.push({row - 1, col});\n }\n if (row + 1 < n && grid[row + 1][col] == 1) { // Move down\n grid[row + 1][col] = -1;\n q.push({row + 1, col});\n }\n if (col - 1 >= 0 && grid[row][col - 1] == 1) { // Move left\n grid[row][col - 1] = -1;\n q.push({row, col - 1});\n }\n if (col + 1 < m && grid[row][col + 1] == 1) { // Move right\n grid[row][col + 1] = -1;\n q.push({row, col + 1});\n }\n }\n }\n bool isConnected(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n vector<vector<int>> tempGrid = grid;\n bool foundIsland = false;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < m; ++j) {\n if (tempGrid[i][j] == 1) {\n bfs(i, j, tempGrid);\n foundIsland = true;\n break;\n }\n }\n if (foundIsland)\n break;\n }\n if(!foundIsland)\n return false;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < m; ++j) {\n if (tempGrid[i][j] == 1) {\n return false;\n }\n }\n }\n return true;\n }\n int minDays(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n if (!isConnected(grid)) {\n return 0;\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (!isConnected(grid)) {\n return 1;\n }\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | C++ || DFS | c-dfs-by-akash92-xs3s | Intuition\n Describe your first thoughts on how to solve this problem. \nNo matter what, we can always disconnect islands in 2 days at max.\nHow so?\nin a group | akash92 | NORMAL | 2024-08-11T06:52:12.827911+00:00 | 2024-08-11T06:52:12.827951+00:00 | 417 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNo matter what, we can always disconnect islands in 2 days at max.\nHow so?\nin a group of islands, delete the two islands(right and bottom) of the top left corner island.\nthis means we need to check if it can be done in less than 2 days or not, if yes then that\'s the minimum answer, otherwise 2 is the answer\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfirst check whether the grid already contains disconnected inslands.\n(use dfs to count number of connected components)\nif not found, then check for 2nd case, that is, 1 day\niterate in grid and check for each cell that is 1 by converting it to 0 and counting number of connected components.\nif more than 1 component found at any cell, return 1\n\nNow after handling both the cases, still the grid is connected, that means we need 2 days to disconnect it\n\n# Complexity\n- Time complexity: $$O(m^2*n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nprivate:\n void dfs(int r, int c, vector<vector<int>>& vis, vector<vector<int>>& grid){\n int m = grid.size(), n = grid[0].size();\n vis[r][c] = 1;\n int dr[4] = {-1,0,1,0};\n int dc[4] = {0,1,0,-1};\n for(int i=0; i<4; i++){\n int nr = r+dr[i];\n int nc = c+dc[i];\n if(nr>=0 && nr<m && nc>=0 && nc<n && grid[nr][nc]==1 && !vis[nr][nc]){\n dfs(nr,nc,vis,grid);\n }\n }\n }\n int islands(vector<vector<int>>& grid){\n int m = grid.size();\n int n = grid[0].size();\n vector<vector<int>> vis(m, vector<int>(n, 0));\n int cnt = 0;\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(grid[i][j]==1 && !vis[i][j]){\n cnt++;\n dfs(i,j,vis,grid);\n }\n }\n }\n return cnt;\n }\npublic:\n int minDays(vector<vector<int>>& grid) {\n if(islands(grid)!=1) return 0;\n\n int m = grid.size();\n int n = grid[0].size();\n\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(grid[i][j]==1){\n grid[i][j]=0;\n if(islands(grid)!=1) return 1;\n grid[i][j]=1;\n }\n }\n }\n\n return 2;\n } \n};\n``` | 2 | 0 | ['Depth-First Search', 'Matrix', 'C++'] | 1 |
minimum-number-of-days-to-disconnect-island | BRUTE FOCE SOLUTION || DFS || WITH EXPLANATION | brute-foce-solution-dfs-with-explanation-uzfb | Intuition\n Describe your first thoughts on how to solve this problem. \n1. Connected Components (Islands): An island is a group of connected land cells (1s). C | ManaviArora | NORMAL | 2024-08-11T06:26:01.697355+00:00 | 2024-08-11T06:26:01.697389+00:00 | 104 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. `Connected Components (Islands):` An island is a group of connected land cells (1s). Connectivity is defined in the four cardinal directions: up, down, left, and right.\n2. `Island Removal Impact:` By removing one cell, you might either:\n * Completely separate an island into multiple islands (if the removed cell was crucial for connectivity).\n * Split the grid into more than one island or break a large island into several parts.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. `Count Islands Function:`\n\n* This function uses Depth-First Search (DFS) to count the number of distinct islands in the grid.\n* It initializes a vis (visited) matrix to keep track of visited cells.\n* For each unvisited land cell, it starts a DFS to mark the entire island and increments the island count.\n2. `Minimum Days Calculation:`\n\n* First, it checks the total number of islands in the initial grid configuration.\n* If there are no islands or more than one island, it returns 0 because the grid is already in a state where removing any one cell would not change the fact that there are 0 or multiple islands.\n* If there is exactly one island, it iterates through each cell in the grid:\n * For each land cell, temporarily removes it (sets it to 0), then counts the number of islands in the modified grid.\n * If removing that cell results in more than one island or no islands (which means the removal splits the island into multiple parts or completely removes it), then it returns 1 because only one day is required to ensure that removing any land cell will disrupt the island connectivity.\n * If removing the cell does not change the count of islands (i.e., it remains 1), it restores the cell and continues.\n* If none of the cells, when removed, split the island, it concludes that at least two days are needed (one for each possible split), so it returns 2.\n\n# Complexity\n- Time complexity: O((m * n)^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m * n) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n void dfs(int i, int j,vector<vector<int>>& grid, vector<vector<bool>> &vis){\n if(i<0 || j<0 || i>=grid.size() || j>= grid[0].size() || grid[i][j] == 0 || vis[i][j] == true) return;\n vis[i][j] = true;\n dfs(i+1,j,grid,vis);\n dfs(i,j+1,grid,vis);\n dfs(i-1,j,grid,vis);\n dfs(i,j-1,grid,vis); \n }\n\n int count_islands(vector<vector<int>>& grid){\n vector<vector<bool>> vis(grid.size(), vector<bool>(grid[0].size(),false));\n int cnt =0 ;\n for(int i=0; i<grid.size(); i++){\n for(int j=0; j<grid[i].size(); j++){\n if(grid[i][j] == 1 && !vis[i][j]){\n cnt++;\n dfs(i,j,grid,vis);\n }\n }\n }\n return cnt;\n }\n int minDays(vector<vector<int>>& grid) {\n if(count_islands(grid) == 0 || count_islands(grid)> 1) return 0;\n \n for(int i=0; i<grid.size(); i++){\n for(int j=0;j<grid[i].size(); j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n int cnt = count_islands(grid);\n if(cnt > 1 || cnt == 0) return 1;\n else grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n};\n```\n> ### PLEASE CONSIDER UPVOTING IF YOU LIKE THE SOLUTION. | 2 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'Strongly Connected Component', 'C++'] | 1 |
minimum-number-of-days-to-disconnect-island | 🌟 Mastering Island Disconnect in 2 Days with Multi-Language Solutions 🔥💯 | mastering-island-disconnect-in-2-days-wi-5ynj | \n\nExplore a collection of solutions to LeetCode problems in multiple programming languages. Each solution includes a detailed explanation and step-by-step app | withaarzoo | NORMAL | 2024-08-11T06:01:55.528465+00:00 | 2024-08-11T06:01:55.528565+00:00 | 504 | false | \n\nExplore a collection of solutions to LeetCode problems in multiple programming languages. Each solution includes a detailed explanation and step-by-step approach to solving the problem efficiently. Whether you\'re a beginner looking to learn or an experienced coder seeking optimized solutions, this repository aims to provide clear and insightful approaches to tackling challenging LeetCode problems.\n\n### **Access daily LeetCode Solutions Repo :** [click here](https://github.com/withaarzoo/LeetCode-Solutions)\n\n---\n\n\n\n## Intuition\nTo disconnect an island in the minimum number of days, the problem can be approached by simulating the disconnection process. Since the island is defined by connected land cells, the goal is to identify the minimum number of land cells that need to be changed to water to split the island into two or more disconnected parts. We start by checking if the grid is already disconnected. If not, we explore changing one or two cells to achieve disconnection, knowing that fewer changes are preferable.\n\n## Approach\n1. **Initial Check**: First, determine if the grid is already disconnected. If it is, return `0`.\n2. **Single Cell Removal**: Iterate through each cell in the grid. For each land cell, temporarily change it to water and check if this causes the grid to disconnect. If so, return `1`.\n3. **Two Cell Removal**: If no single cell disconnection is found, attempt to disconnect the grid by changing any two land cells. If this results in disconnection, return `2`.\n4. **BFS/DFS for Connectivity Check**: Use BFS (Breadth-First Search) to explore the island and check if it remains connected after each change.\n\n## Complexity\n- **Time Complexity**: \n - The time complexity is approximately $$O(m \\times n \\times (m \\times n))$$ where \\(m\\) and \\(n\\) are the grid dimensions. This accounts for the BFS/DFS traversal needed to check connectivity after potentially removing every land cell.\n \n- **Space Complexity**:\n - The space complexity is $$O(m \\times n)$$ due to the space needed to store the visited nodes during BFS/DFS traversal.\n\n## Code\n```C++ []\nclass Solution {\npublic:\n int minDays(vector<vector<int>>& grid) {\n if (isDisconnected(grid)) return 0;\n\n int m = grid.size();\n int n = grid[0].size();\n\n // Try removing one cell\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (isDisconnected(grid)) return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n // Try removing two cells\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n for (int x = 0; x < m; ++x) {\n for (int y = 0; y < n; ++y) {\n if (grid[x][y] == 1) {\n grid[x][y] = 0;\n if (isDisconnected(grid)) return 2;\n grid[x][y] = 1;\n }\n }\n }\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n\nprivate:\n bool isDisconnected(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n vector<vector<int>> visited(m, vector<int>(n, 0));\n\n int landCount = 0;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n ++landCount;\n if (!visited[i][j]) {\n if (landCount > 1) return true;\n bfs(grid, visited, i, j);\n }\n }\n }\n }\n return landCount == 0;\n }\n\n void bfs(vector<vector<int>>& grid, vector<vector<int>>& visited, int i, int j) {\n int m = grid.size();\n int n = grid[0].size();\n queue<pair<int, int>> q;\n q.push({i, j});\n visited[i][j] = 1;\n\n vector<int> dirX = {-1, 1, 0, 0};\n vector<int> dirY = {0, 0, -1, 1};\n\n while (!q.empty()) {\n auto [x, y] = q.front();\n q.pop();\n\n for (int d = 0; d < 4; ++d) {\n int newX = x + dirX[d];\n int newY = y + dirY[d];\n if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == 1 && !visited[newX][newY]) {\n visited[newX][newY] = 1;\n q.push({newX, newY});\n }\n }\n }\n }\n};\n\n```\n```Java []\nclass Solution {\n public int minDays(int[][] grid) {\n if (isDisconnected(grid)) return 0;\n\n int m = grid.length;\n int n = grid[0].length;\n\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (isDisconnected(grid)) return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n for (int x = 0; x < m; ++x) {\n for (int y = 0; y < n; ++y) {\n if (grid[x][y] == 1) {\n grid[x][y] = 0;\n if (isDisconnected(grid)) return 2;\n grid[x][y] = 1;\n }\n }\n }\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n\n private boolean isDisconnected(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n boolean[][] visited = new boolean[m][n];\n\n int landCount = 0;\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n ++landCount;\n if (!visited[i][j]) {\n if (landCount > 1) return true;\n bfs(grid, visited, i, j);\n }\n }\n }\n }\n return landCount == 0;\n }\n\n private void bfs(int[][] grid, boolean[][] visited, int i, int j) {\n int m = grid.length;\n int n = grid[0].length;\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[]{i, j});\n visited[i][j] = true;\n\n int[] dirX = {-1, 1, 0, 0};\n int[] dirY = {0, 0, -1, 1};\n\n while (!q.isEmpty()) {\n int[] current = q.poll();\n int x = current[0];\n int y = current[1];\n\n for (int d = 0; d < 4; ++d) {\n int newX = x + dirX[d];\n int newY = y + dirY[d];\n if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == 1 && !visited[newX][newY]) {\n visited[newX][newY] = true;\n q.offer(new int[]{newX, newY});\n }\n }\n }\n }\n}\n\n```\n```JavaScript []\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minDays = function(grid) {\n if (isDisconnected(grid)) return 0;\n\n const m = grid.length;\n const n = grid[0].length;\n\n // Try removing one cell\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0;\n if (isDisconnected(grid)) return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n // Try removing two cells\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0;\n for (let x = 0; x < m; ++x) {\n for (let y = 0; y < n; ++y) {\n if (grid[x][y] === 1) {\n grid[x][y] = 0;\n if (isDisconnected(grid)) return 2;\n grid[x][y] = 1;\n }\n }\n }\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n};\n\nfunction isDisconnected(grid) {\n const m = grid.length;\n const n = grid[0].length;\n const visited = Array.from({ length: m }, () => Array(n).fill(false));\n\n let landCount = 0;\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (grid[i][j] === 1) {\n ++landCount;\n if (!visited[i][j]) {\n if (landCount > 1) return true;\n bfs(grid, visited, i, j);\n }\n }\n }\n }\n return landCount === 0;\n}\n\nfunction bfs(grid, visited, i, j) {\n const m = grid.length;\n const n = grid[0].length;\n const queue = [[i, j]];\n visited[i][j] = true;\n\n const dirX = [-1, 1, 0, 0];\n const dirY = [0, 0, -1, 1];\n\n while (queue.length > 0) {\n const [x, y] = queue.shift();\n\n for (let d = 0; d < 4; ++d) {\n const newX = x + dirX[d];\n const newY = y + dirY[d];\n if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] === 1 && !visited[newX][newY]) {\n visited[newX][newY] = true;\n queue.push([newX, newY]);\n }\n }\n }\n}\n\n```\n```Python []\nfrom collections import deque\nfrom typing import List\n\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n if self.isDisconnected(grid):\n return 0\n\n m, n = len(grid), len(grid[0])\n\n # Try removing one cell\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n grid[i][j] = 0\n if self.isDisconnected(grid):\n return 1\n grid[i][j] = 1\n\n # Try removing two cells\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n grid[i][j] = 0\n for x in range(m):\n for y in range(n):\n if grid[x][y] == 1:\n grid[x][y] = 0\n if self.isDisconnected(grid):\n return 2\n grid[x][y] = 1\n grid[i][j] = 1\n return 2\n\n def isDisconnected(self, grid: List[List[int]]) -> bool:\n m, n = len(grid), len(grid[0])\n visited = [[0] * n for _ in range(m)]\n\n land_count = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n land_count += 1\n if not visited[i][j]:\n if land_count > 1:\n return True\n self.bfs(grid, visited, i, j)\n return land_count == 0\n\n def bfs(self, grid: List[List[int]], visited: List[List[int]], i: int, j: int) -> None:\n m, n = len(grid), len(grid[0])\n queue = deque([(i, j)])\n visited[i][j] = 1\n\n dirX = [-1, 1, 0, 0]\n dirY = [0, 0, -1, 1]\n\n while queue:\n x, y = queue.popleft()\n\n for d in range(4):\n newX = x + dirX[d]\n newY = y + dirY[d]\n if 0 <= newX < m and 0 <= newY < n and grid[newX][newY] == 1 and not visited[newX][newY]:\n visited[newX][newY] = 1\n queue.append((newX, newY))\n\n```\n```Go []\nfunc minDays(grid [][]int) int {\n if isDisconnected(grid) {\n return 0\n }\n\n m, n := len(grid), len(grid[0])\n\n for i := 0; i < m; i++ {\n for j := 0; j < n; j++ {\n if grid[i][j] == 1 {\n grid[i][j] = 0\n if isDisconnected(grid) {\n return 1\n }\n grid[i][j] = 1\n }\n }\n }\n\n for i := 0; i < m; i++ {\n for j := 0; j < n; j++ {\n if grid[i][j] == 1 {\n grid[i][j] = 0\n for x := 0; x < m; x++ {\n for y := 0; y < n; y++ {\n if grid[x][y] == 1 {\n grid[x][y] = 0\n if isDisconnected(grid) {\n return 2\n }\n grid[x][y] = 1\n }\n }\n }\n grid[i][j] = 1\n }\n }\n }\n return 2\n}\n\nfunc isDisconnected(grid [][]int) bool {\n m, n := len(grid), len(grid[0])\n visited := make([][]bool, m)\n for i := range visited {\n visited[i] = make([]bool, n)\n }\n\n landCount := 0\n for i := 0; i < m; i++ {\n for j := 0; j < n; j++ {\n if grid[i][j] == 1 {\n landCount++\n if !visited[i][j] {\n if landCount > 1 {\n return true\n }\n bfs(grid, visited, i, j)\n }\n }\n }\n }\n return landCount == 0\n}\n\nfunc bfs(grid [][]int, visited [][]bool, i, j int) {\n m, n := len(grid), len(grid[0])\n dirX := []int{-1, 1, 0, 0}\n dirY := []int{0, 0, -1, 1}\n\n queue := [][]int{{i, j}}\n visited[i][j] = true\n\n for len(queue) > 0 {\n x, y := queue[0][0], queue[0][1]\n queue = queue[1:]\n\n for d := 0; d < 4; d++ {\n newX, newY := x+dirX[d], y+dirY[d]\n if newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == 1 && !visited[newX][newY] {\n visited[newX][newY] = true\n queue = append(queue, []int{newX, newY})\n }\n }\n }\n}\n\n```\n\n\n## Step-by-Step Detailed Explanation\n1. **Initial Check**: The first step in the `minDays` function is to check if the grid is already disconnected using the `isDisconnected` function. This function counts the number of separate connected components of land cells (1\'s). If there is more than one, it returns `0`, indicating that the grid is already disconnected.\n\n2. **Single Cell Removal**: If the grid is still connected, the next step is to iterate through each cell in the grid. If a cell contains land (`1`), it temporarily changes the cell to water (`0`) and checks if the grid becomes disconnected. If it does, the function returns `1`, indicating that one day is sufficient to disconnect the grid.\n\n3. **Two Cell Removal**: If removing a single cell does not disconnect the grid, the function then tries removing combinations of two cells. It iterates through each cell and, for each cell that contains land, temporarily changes it to water. It then checks the grid again after removing another land cell. If this disconnects the grid, the function returns `2`.\n\n4. **BFS for Connectivity Check**: The `isDisconnected` function uses BFS (Breadth-First Search) to explore the island starting from any land cell. It marks cells as visited and ensures all connected cells are part of the same island. If multiple unconnected land areas are found, the grid is considered disconnected.\n\n---\n\n\n | 2 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript'] | 2 |
minimum-number-of-days-to-disconnect-island | Java Solution Using GraphBFS Traversal || SCC Typically Question | java-solution-using-graphbfs-traversal-s-6tr7 | Complexity\n- Time complexity:O((n+m)*4Alpha)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n Add your space complexity here, e.g. O(n) \n\ | Shree_Govind_Jee | NORMAL | 2024-08-11T04:15:25.728138+00:00 | 2024-08-11T04:15:25.728163+00:00 | 277 | false | # Complexity\n- Time complexity:$$O((n+m)*4Alpha)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n int[] dir_X = { 1, -1, 0, 0 };\n int[] dir_Y = { 0, 0, 1, -1 };\n\n private void solveBFS(int[][] res, int r, int c, int n, int m) {\n boolean[][] vis = new boolean[n][m];\n vis[r][c] = true;\n\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[] { r, c });\n\n while (!q.isEmpty()) {\n int[] top = q.remove();\n\n for (int i = 0; i < 4; i++) {\n int nr = dir_X[i] + top[0];\n int nc = dir_Y[i] + top[1];\n if (nr >= 0 && nr < n && nc >= 0 && nc < m &&\n !vis[nr][nc] && res[nr][nc] == 1) {\n vis[nr][nc] = true;\n res[nr][nc] = 0;\n q.offer(new int[] { nr, nc });\n }\n }\n }\n }\n\n\n public int minDays(int[][] grid) {\n int n = grid.length;\n int m = grid[0].length;\n\n ArrayList<int[]> list = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n list.add(new int[] { i, j });\n }\n }\n }\n\n int[][] res = new int[n][m];\n for (int i = 0; i < n; i++) {\n res[i] = Arrays.copyOf(grid[i], grid[i].length);\n }\n\n int ans = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (res[i][j] == 1) {\n solveBFS(res, i, j, n, m);\n ans++;\n }\n }\n }\n if (ans > 1 || ans == 0) {\n return 0;\n }\n\n for (int i = 0; i < list.size(); i++) {\n int r = list.get(i)[0];\n int c = list.get(i)[1];\n\n res = new int[n][m];\n for (int k = 0; k < n; k++) {\n res[k] = Arrays.copyOf(grid[k], grid[k].length);\n }\n\n res[r][c] = 0;\n ans = 0;\n for (int j = 0; j < n; j++) {\n for (int k = 0; k < m; k++) {\n if (res[j][k] == 1) {\n solveBFS(res, j, k, n, m);\n ans++;\n }\n }\n }\n if (ans > 1 || ans == 0) {\n return 1;\n }\n }\n return 2;\n }\n}\n``` | 2 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'Strongly Connected Component', 'Java'] | 2 |
minimum-number-of-days-to-disconnect-island | C++ || Easy Video Solution | c-easy-video-solution-by-n_i_v_a_s-o57k | The video solution for the below code is\nhttps://youtu.be/dDfY6llzsu8\n\n# Code\n\nclass Solution {\npublic:\n int minDays(vector<vector<int>>& grid) {\n | __SAI__NIVAS__ | NORMAL | 2024-08-11T04:08:34.745360+00:00 | 2024-08-11T04:08:34.745377+00:00 | 436 | false | The video solution for the below code is\nhttps://youtu.be/dDfY6llzsu8\n\n# Code\n```\nclass Solution {\npublic:\n int minDays(vector<vector<int>>& grid) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n // Note : Grid is said to be connected if there is excatly one island in it.\n // In one day we are allowd to change one land cell into water cell.\n // We need to return the minimum number of days to disconnect the grid.\n // Step - 1 : Count the number of islands that are present in the grid.\n vector<vector<int>> tmpGridStart(grid);\n // The grid is disconnected either if number of islands are 0 or number of islands are greater than or equal to 2.\n int rows = grid.size();\n int cols = grid[0].size();\n if(countNumberOfIslands(grid) != 1) return 0;\n for(int i = 0 ; i < rows ; i++){\n for(int j = 0 ; j < cols ; j++){\n grid[i][j] = tmpGridStart[i][j];\n }\n }\n // The other finding of the problem\n // Given any shape of grid and the grid is having ones and zeros then the max number of islands that needs to be changed to make grid disconnected according to the given condition is 2\n for(int i = 0 ; i < rows ; i++){\n for(int j = 0 ; j < cols ; j++){\n if(grid[i][j] == 0) continue;\n vector<vector<int>> tmpGrid(grid);\n grid[i][j] = 0;\n int ans = countNumberOfIslands(grid);\n if(ans != 1) return 1;\n for(int a = 0 ; a < rows ; a++){\n for(int b = 0 ; b < cols ; b++){\n grid[a][b] = tmpGrid[a][b];\n }\n }\n }\n }\n return 2;\n }\n int countNumberOfIslands(vector<vector<int>> &grid){\n // Variable to store the number of islands\n int islands = 0;\n int rows = grid.size();\n int cols = grid[0].size();\n for(int i = 0 ; i < rows ; i++){\n for(int j = 0 ; j < cols ; j++){\n if(grid[i][j] == 1){\n islands += 1;\n changeGrid(grid, i, j);\n }\n }\n }\n return islands;\n }\n void changeGrid(vector<vector<int>> &grid, int row, int col){\n int rows = grid.size();\n int cols = grid[0].size();\n queue<pair<int, int>> q;\n grid[row][col] = 0;\n vector<int> dr[4] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};\n q.push({row, col});\n while(!q.empty()){\n auto front = q.front();\n q.pop();\n for(auto &ele : dr){\n int tmpR = ele[0] + front.first;\n int tmpC = ele[1] + front.second;\n if(tmpR >= 0 and tmpR < rows and tmpC >= 0 and tmpC < cols and grid[tmpR][tmpC] == 1){\n grid[tmpR][tmpC] = 0;\n q.push({tmpR, tmpC});\n }\n }\n }\n\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
minimum-number-of-days-to-disconnect-island | C# Solution for Minimum Number of Days to Disconnect Island Problem | c-solution-for-minimum-number-of-days-to-s9kt | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this approach is to treat the grid as a graph where each cell repr | Aman_Raj_Sinha | NORMAL | 2024-08-11T03:04:08.313763+00:00 | 2024-08-11T03:04:08.313789+00:00 | 122 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this approach is to treat the grid as a graph where each cell represents a node. The idea is to identify \u201Ccritical cells\u201D (similar to bridges in graph theory) that, when removed, increase the number of islands (connected components) in the grid. If such a critical cell exists, it means the grid can be disconnected by removing just that cell, requiring only one day. If no such cell exists, disconnecting the grid will require at least two days.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tCheck if the Grid is Already Disconnected:\n\t\u2022\tCount the number of islands in the grid using DFS. If there is more than one island initially, return 0 since the grid is already disconnected.\n2.\tIdentify Bridge-like (Critical) Cells:\n\t\u2022\tFor each cell in the grid, temporarily change it from land (1) to water (0).\n\t\u2022\tRecount the number of islands in the modified grid.\n\t\u2022\tIf the number of islands increases after removing the cell, it means that cell was critical to maintaining connectivity. In this case, return 1 because removing just this one cell disconnects the grid.\n3.\tNo Critical Cells:\n\t\u2022\tIf no single cell can disconnect the grid, return 2. This is because if the grid remains connected after any single removal, it will require removing at least two cells to disconnect the grid.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tCounting Islands: The CountIslands function uses DFS, which has a time complexity of O(m x n), where m is the number of rows and n is the number of columns.\n\u2022\tIterating Over Each Cell: For each land cell, we simulate its removal and recount the islands. In the worst case, this process will be repeated for every cell in the grid. Thus, this results in a time complexity of O(m x n x m x n).\n\u2022\tOverall Time Complexity: The overall time complexity of this approach is O(m^2 x n^2), which is the same as the previous approach.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tSpace for Visited Array: The visited array used in DFS takes up O(m x n) space.\n\u2022\tStack Space for DFS: The DFS stack space is O(m x n) in the worst case.\n\u2022\tOverall Space Complexity: The overall space complexity is O(m x n).\n\n# Code\n```\npublic class Solution {\n public int MinDays(int[][] grid) {\n // Step 1: Check if the grid is already disconnected.\n if (CountIslands(grid) != 1) {\n return 0;\n }\n\n // Step 2: Check for bridge-like cells.\n int rows = grid.Length;\n int cols = grid[0].Length;\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n // Remove this land temporarily\n grid[i][j] = 0;\n if (CountIslands(grid) != 1) {\n return 1;\n }\n // Restore the land\n grid[i][j] = 1;\n }\n }\n }\n\n // Step 3: If no bridge-like cell exists, return 2.\n return 2;\n }\n\n private int CountIslands(int[][] grid) {\n int rows = grid.Length;\n int cols = grid[0].Length;\n bool[,] visited = new bool[rows, cols];\n int islandCount = 0;\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1 && !visited[i, j]) {\n islandCount++;\n DFS(grid, visited, i, j);\n }\n }\n }\n\n return islandCount;\n }\n\n private void DFS(int[][] grid, bool[,] visited, int i, int j) {\n int[] dx = {-1, 1, 0, 0};\n int[] dy = {0, 0, -1, 1};\n\n visited[i, j] = true;\n\n for (int k = 0; k < 4; k++) {\n int newX = i + dx[k];\n int newY = j + dy[k];\n\n if (newX >= 0 && newX < grid.Length && newY >= 0 && newY < grid[0].Length &&\n grid[newX][newY] == 1 && !visited[newX, newY]) {\n DFS(grid, visited, newX, newY);\n }\n }\n }\n}\n``` | 2 | 0 | ['C#'] | 1 |
minimum-number-of-days-to-disconnect-island | Swift | 2 days are enough 🏄 | swift-2-days-are-enough-by-pagafan7as-0fkn | The key to solving this problem is to notice that the solution is either 0, 1 or 2 days.\n\nProof: If there is at least one square with land, go up and right as | pagafan7as | NORMAL | 2024-08-11T01:07:30.411385+00:00 | 2024-08-11T02:38:37.340870+00:00 | 48 | false | The key to solving this problem is to notice that the solution is either 0, 1 or 2 days.\n\n**Proof:** If there is at least one square with land, go up and right as long as there is land. You will end up at a land square from where you cannot proceed, with water above and to the right. This land square can be made disconnected from the rest by making its 2 neighbors below and to the left water. Therefore 2 days are enough.\n\nThis property leads to the following algorithm:\n\nUse DFS and look if the grid, as is, is disconnected, that is check whether there are 0 or 2 or more islands: 0 days.\n\nOtherwise, for each land square, remove it and see if the grid becomes disconnected: 1 day.\n\nIf this is not the case, we know by the proof above, that it will take 2 days.\n\n# Code\n```\nclass Solution {\n func minDays(_ grid: [[Int]]) -> Int {\n let m = grid.count, n = grid[0].count\n var grid = grid\n\n if isDisconnected(grid) { return 0 } \n\n for r in 0..<m {\n for c in 0..<n where grid[r][c] == 1 {\n grid[r][c] = 0\n if isDisconnected(grid) { return 1 }\n grid[r][c] = 1\n }\n }\n\n return 2\n\n func isDisconnected(_ grid: [[Int]]) -> Bool {\n var grid = grid\n var islands = 0\n for r in 0..<m {\n for c in 0..<n where grid[r][c] == 1 {\n dfs(r, c)\n islands += 1\n }\n }\n return islands != 1\n\n func dfs(_ r: Int, _ c: Int) {\n if r < 0 || r >= m || c < 0 || c >= n { return }\n if grid[r][c] != 1 { return }\n grid[r][c] = 2\n for dir in [(1, 0), (-1, 0), (0, 1), (0, -1)] {\n dfs(r + dir.0, c + dir.1)\n }\n }\n }\n }\n}\n``` | 2 | 0 | ['Swift'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy Solution | easy-solution-by-sachinonly-j8mo | Intuition\nview the hint section and for better understanding view editorial\n\n# Approach\n1. Count Islands:\n - A helper function countIslands is used to c | Sachinonly__ | NORMAL | 2024-08-11T00:44:32.717920+00:00 | 2024-08-11T12:07:16.313422+00:00 | 371 | false | # Intuition\nview the hint section and for better understanding view editorial\n\n# Approach\n1. **Count Islands:**\n - A helper function countIslands is used to count the number of islands in the grid using Depth-First Search (DFS).\n - It initializes a visited matrix to keep track of visited cells and a counter islands to count the number of connected components (islands).\n - The DFS explores all connected 1s from each unvisited cell.\n2. **Initial Check:**\n\n - Before trying to remove any cell, the code checks if the grid already has more than one island. If yes, the function returns 0 since the island is already disconnected.\n3. **Simulate Removing Each Land Cell:**\n\n - The code tries to remove each land cell (turn it into water) and checks if it disconnects the island using the countIslands function.\n - If any removal results in more than one island, the function returns 1.\n4. **Final Step:**\n\n - If no single cell removal disconnects the island, the function returns 2 because removing any two land cells will always disconnect the island.\n\n# Code\n```python []\nclass Solution(object):\n def minDays(self, grid):\n def countIslands():\n # Count the number of islands in the grid using DFS\n visited = [[False] * n for _ in range(m)]\n islands = 0\n \n def dfs(x, y):\n if x < 0 or x >= m or y < 0 or y >= n or grid[x][y] == 0 or visited[x][y]:\n return\n visited[x][y] = True\n dfs(x + 1, y)\n dfs(x - 1, y)\n dfs(x, y + 1)\n dfs(x, y - 1)\n \n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and not visited[i][j]:\n islands += 1\n dfs(i, j)\n return islands\n \n m, n = len(grid), len(grid[0])\n \n # Step 1: Check if the island is already disconnected\n if countIslands() != 1:\n return 0\n \n # Step 2: Try removing each land cell\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n grid[i][j] = 0\n if countIslands() != 1:\n return 1\n grid[i][j] = 1\n \n # Step 3: If no single cell removal disconnects the island, return 2\n return 2\n```\n```C++ []\n#include <vector>\n\nusing namespace std;\n\nclass Solution {\npublic:\n int minDays(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n \n // Function to count the number of islands\n auto countIslands = [&]() {\n vector<vector<bool>> visited(m, vector<bool>(n, false));\n int islands = 0;\n\n // Lambda function for DFS\n function<void(int, int)> dfs = [&](int x, int y) {\n if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0 || visited[x][y])\n return;\n visited[x][y] = true;\n dfs(x + 1, y);\n dfs(x - 1, y);\n dfs(x, y + 1);\n dfs(x, y - 1);\n };\n\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n islands++;\n dfs(i, j);\n }\n }\n }\n return islands;\n };\n\n // Step 1: Check if the island is already disconnected\n if (countIslands() != 1) {\n return 0;\n }\n\n // Step 2: Try removing each land cell\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (countIslands() != 1) {\n return 1;\n }\n grid[i][j] = 1;\n }\n }\n }\n\n // Step 3: If no single cell removal disconnects the island, return 2\n return 2;\n }\n};\n```\n\n | 2 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'Strongly Connected Component', 'Python', 'C++', 'Python3'] | 1 |
minimum-number-of-days-to-disconnect-island | O(m * n) | DFS | Beats 100% Java | C++ | Python | Go | Rust | JavaScript | om-n-dfs-beats-100-java-c-python-go-rust-szcp | Intuition\n\nThis problem is fundamentally a graph theory problem. The key insight is to recognize that we\'re dealing with a connected component (the island) i | kartikdevsharma_ | NORMAL | 2024-08-09T12:05:23.305727+00:00 | 2024-08-09T12:41:04.281545+00:00 | 358 | false | ### Intuition\n\nThis problem is fundamentally a graph theory problem. The key insight is to recognize that we\'re dealing with a connected component (the island) in a graph (the grid), and we need to find the most efficient way to break this component.\n\nInitially, one might think of simply removing land cells one by one until the island is disconnected. However, this brute force approach would be inefficient for larger grids. A more sophisticated approach is to use the concept of articulation points from graph theory.\n\nAn articulation point, also known as a cut vertex, is a vertex in a graph whose removal increases the number of connected components. In the context of our island problem, an articulation point would be a land cell that, when removed, splits the island into two or more separate pieces.\n\nThe intuition here is that if we can find an articulation point in our island, we can disconnect it by removing just that single cell, which would take only one day. If no such point exists, we know we\'ll need to remove at least two cells to disconnect the island.\n\nThis leads us to Tarjan\'s algorithm, a depth-first search (DFS) based approach that can efficiently identify articulation points in a graph. By adapting this algorithm to our grid-based problem, we can determine whether we can disconnect the island in one day or if we need two days.\n\n### Approach\n\nOur approach can be broken down into several key steps:\n\n**1. Initial Grid Analysis:**\n We start by analyzing the initial state of the grid. We need to count the number of islands and the total number of land cells. This initial check helps us handle several edge cases:\n - If there are no land cells or more than one island, we can return 0 as the grid is already disconnected.\n - If there\'s only one land cell, we return 1 as removing it will disconnect the grid in one day.\n\n**2. Depth-First Search (DFS) Traversal:**\n We use a DFS to explore the island. This traversal serves two purposes:\n - It confirms that we indeed have a single connected island.\n - It allows us to identify articulation points using Tarjan\'s algorithm.\n\n**3. Articulation Point Detection:**\n During the DFS traversal, we keep track of three key pieces of information for each cell:\n - Discovery time: When the cell is first visited during the DFS.\n - Lowest reachable time: The minimum discovery time of any cell that can be reached from the subtree rooted at the current cell, including the cell itself.\n - Parent: The cell from which we reached the current cell during the DFS.\n\n Using these, we can identify articulation points:\n - For a non-root cell: If it has a child whose lowest reachable time is greater than or equal to its own discovery time, it\'s an articulation point.\n - For the root cell: If it has more than one child in the DFS tree, it\'s an articulation point.\n\n**4. Result Determination:**\n - If we find any articulation point, we return 1, as removing that point will disconnect the island in one day.\n - If no articulation point is found, we return 2, as we\'ll need to remove any two land cells to guarantee disconnection.\n\n**Implementation**\n\n1. **Class Structure and Variables:**\n\n We define a Solution class with several member variables:\n - time: A counter for the DFS discovery time.\n - discoveryTime and lowestReachableTime: 2D arrays to store these values for each cell.\n - DIRECTIONS: An array of coordinate pairs representing the four adjacent directions (right, down, left, up).\n - hasArticulationPoint: A boolean flag to indicate if we\'ve found an articulation point.\n - totalLandCells: A counter for the total number of land cells.\n\n**2. Main Method (minDays):**\n\n This method orchestrates the overall solution:\n - It initializes our data structures and variables.\n - It iterates through the grid to find land cells and start the DFS.\n - It handles edge cases (no land, single land cell, multiple islands).\n - It returns the final result based on whether an articulation point was found.\n\n**3. DFS Method:**\n\n This is where the core of Tarjan\'s algorithm is implemented:\n - It assigns discovery and lowest reachable times to the current cell.\n - It explores adjacent land cells recursively.\n - It updates the lowest reachable time based on explored neighbors.\n - It checks for articulation point conditions and sets the flag if found.\n\n**4. Helper Methods:**\n - isValidCell: Checks if a given cell is within the grid bounds and is a land cell.\n\nLet\'s walk through the DFS method in more detail, as it\'s the heart of our solution:\n\n1. We start by assigning the current time as both the discovery time and lowest reachable time for the current cell. We then increment the time counter.\n\n2. We increment the totalLandCells counter, as we\'ve found a new land cell.\n\n3. We initialize a children counter to keep track of how many children this cell has in the DFS tree.\n\n4. We then loop through all four adjacent directions:\n - For each direction, we calculate the new row and column.\n - We check if the new cell is valid (within bounds and a land cell).\n - If the new cell hasn\'t been discovered yet (discovery time is 0):\n * We increment the children counter.\n * We recursively call DFS on this new cell, passing the current cell as its parent.\n * After the recursive call, we update the lowest reachable time of the current cell based on the lowest reachable time of its child.\n * We check if this child makes the current cell an articulation point. This happens if the lowest reachable time of the child is greater than or equal to the discovery time of the current cell, and the current cell is not the root of the DFS tree.\n - If the new cell has been discovered and is not the parent of the current cell:\n * We update the lowest reachable time of the current cell based on the discovery time of this adjacent cell. This handles back edges in the graph.\n\n5. After exploring all directions, we check if the current cell is the root of the DFS tree (parent is -1) and has more than one child. If so, it\'s an articulation point.\n\n\n\n### Complexity\n\n**Time Complexity:O(m * n)**\nThe time complexity of this solution is O(m * n), where m is the number of rows and n is the number of columns in the grid. This is because:\n- We iterate through each cell in the grid once to start the DFS.\n- The DFS itself visits each land cell exactly once.\n- For each cell, we perform a constant number of operations (checking adjacent cells, updating times, etc.).\n\nEven though we have nested loops in the main method and the DFS method, each cell is only fully processed once, giving us a linear time complexity in terms of the total number of cells.\n\n**Space Complexity:O(m * n)**\nThe space complexity is also O(m * n). This comes from:\n- The discoveryTime and lowestReachableTime arrays, each of which has m * n elements.\n- The recursive call stack of the DFS, which in the worst case (a grid full of land cells arranged in a line) could be m * n deep.\n\nWhile we do use other variables (time, hasArticulationPoint, totalLandCells), these take constant space and don\'t affect the overall space complexity.\n\n\n# Code\n```Java []\nclass Solution {\n private int time;\n private int[][] discoveryTime;\n private int[][] lowestReachableTime;\n private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n private boolean hasArticulationPoint;\n private int totalLandCells;\n\n public int minDays(int[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n discoveryTime = new int[rows][cols];\n lowestReachableTime = new int[rows][cols];\n time = 1;\n hasArticulationPoint = false;\n totalLandCells = 0;\n int islands = 0;\n\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (grid[row][col] == 1 && discoveryTime[row][col] == 0) {\n islands++;\n if (islands > 1) return 0; // More than one island\n dfs(row, col, grid, -1, -1);\n }\n }\n }\n\n if (totalLandCells == 0) return 0; // No land\n if (totalLandCells == 1) return 1; // Only one land cell\n if (islands == 0) return 0; // No islands (should not happen if input is valid)\n return hasArticulationPoint ? 1 : 2;\n }\n\n private void dfs(int row, int col, int[][] grid, int parentRow, int parentCol) {\n discoveryTime[row][col] = time;\n lowestReachableTime[row][col] = time;\n time++;\n totalLandCells++;\n int children = 0;\n\n for (int[] direction : DIRECTIONS) {\n int newRow = row + direction[0];\n int newCol = col + direction[1];\n \n if (!isValidCell(newRow, newCol, grid)) {\n continue;\n }\n \n if (discoveryTime[newRow][newCol] == 0) {\n children++;\n dfs(newRow, newCol, grid, row, col);\n lowestReachableTime[row][col] = Math.min(lowestReachableTime[row][col], lowestReachableTime[newRow][newCol]);\n \n if (lowestReachableTime[newRow][newCol] >= discoveryTime[row][col] && parentRow != -1) {\n hasArticulationPoint = true;\n }\n } else if ((newRow != parentRow || newCol != parentCol) && discoveryTime[newRow][newCol] < discoveryTime[row][col]) {\n lowestReachableTime[row][col] = Math.min(lowestReachableTime[row][col], discoveryTime[newRow][newCol]);\n }\n }\n\n if (parentRow == -1 && children > 1) {\n hasArticulationPoint = true;\n }\n }\n\n private boolean isValidCell(int row, int col, int[][] grid) {\n return row >= 0 && col >= 0 && row < grid.length && col < grid[0].length && grid[row][col] == 1;\n }\n}\n\n\n\n\n//https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/submissions/1349885103/\n```\n```C++ []\nclass Solution {\nprivate:\n int time;\n vector<vector<int>> discoveryTime;\n vector<vector<int>> lowestReachableTime;\n const vector<pair<int, int>> DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n bool hasArticulationPoint;\n int totalLandCells;\n\n void dfs(int row, int col, vector<vector<int>>& grid, int parentRow, int parentCol) {\n discoveryTime[row][col] = time;\n lowestReachableTime[row][col] = time;\n time++;\n totalLandCells++;\n int children = 0;\n\n for (const auto& direction : DIRECTIONS) {\n int newRow = row + direction.first;\n int newCol = col + direction.second;\n \n if (!isValidCell(newRow, newCol, grid)) {\n continue;\n }\n \n if (discoveryTime[newRow][newCol] == 0) {\n children++;\n dfs(newRow, newCol, grid, row, col);\n lowestReachableTime[row][col] = min(lowestReachableTime[row][col], lowestReachableTime[newRow][newCol]);\n \n if (lowestReachableTime[newRow][newCol] >= discoveryTime[row][col] && parentRow != -1) {\n hasArticulationPoint = true;\n }\n } else if ((newRow != parentRow || newCol != parentCol) && discoveryTime[newRow][newCol] < discoveryTime[row][col]) {\n lowestReachableTime[row][col] = min(lowestReachableTime[row][col], discoveryTime[newRow][newCol]);\n }\n }\n\n if (parentRow == -1 && children > 1) {\n hasArticulationPoint = true;\n }\n }\n\n bool isValidCell(int row, int col, const vector<vector<int>>& grid) {\n return row >= 0 && col >= 0 && row < grid.size() && col < grid[0].size() && grid[row][col] == 1;\n }\n\npublic:\n int minDays(vector<vector<int>>& grid) {\n int rows = grid.size(), cols = grid[0].size();\n discoveryTime = vector<vector<int>>(rows, vector<int>(cols, 0));\n lowestReachableTime = vector<vector<int>>(rows, vector<int>(cols, 0));\n time = 1;\n hasArticulationPoint = false;\n totalLandCells = 0;\n int islands = 0;\n\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (grid[row][col] == 1 && discoveryTime[row][col] == 0) {\n islands++;\n if (islands > 1) return 0; // More than one island\n dfs(row, col, grid, -1, -1);\n }\n }\n }\n\n if (totalLandCells == 0) return 0; // No land\n if (totalLandCells == 1) return 1; // Only one land cell\n if (islands == 0) return 0; // No islands (should not happen if input is valid)\n return hasArticulationPoint ? 1 : 2;\n }\n};\n\n\n\n\n\n//https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/submissions/1349890326/\n```\n```Python []\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n self.time = 1\n self.hasArticulationPoint = False\n self.totalLandCells = 0\n DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n rows, cols = len(grid), len(grid[0])\n \n discoveryTime = [[0] * cols for _ in range(rows)]\n lowestReachableTime = [[0] * cols for _ in range(rows)]\n \n def isValidCell(row: int, col: int) -> bool:\n return 0 <= row < rows and 0 <= col < cols and grid[row][col] == 1\n \n def dfs(row: int, col: int, parentRow: int, parentCol: int) -> None:\n nonlocal discoveryTime, lowestReachableTime\n discoveryTime[row][col] = self.time\n lowestReachableTime[row][col] = self.time\n self.time += 1\n self.totalLandCells += 1\n children = 0\n \n for dr, dc in DIRECTIONS:\n newRow, newCol = row + dr, col + dc\n if not isValidCell(newRow, newCol):\n continue\n \n if discoveryTime[newRow][newCol] == 0:\n children += 1\n dfs(newRow, newCol, row, col)\n lowestReachableTime[row][col] = min(lowestReachableTime[row][col], lowestReachableTime[newRow][newCol])\n \n if lowestReachableTime[newRow][newCol] >= discoveryTime[row][col] and parentRow != -1:\n self.hasArticulationPoint = True\n elif (newRow, newCol) != (parentRow, parentCol) and discoveryTime[newRow][newCol] < discoveryTime[row][col]:\n lowestReachableTime[row][col] = min(lowestReachableTime[row][col], discoveryTime[newRow][newCol])\n \n if parentRow == -1 and children > 1:\n self.hasArticulationPoint = True\n \n islands = 0\n for row in range(rows):\n for col in range(cols):\n if grid[row][col] == 1 and discoveryTime[row][col] == 0:\n islands += 1\n if islands > 1:\n return 0 # More than one island\n dfs(row, col, -1, -1)\n \n if self.totalLandCells == 0:\n return 0 # No land\n if self.totalLandCells == 1:\n return 1 # Only one land cell\n if islands == 0:\n return 0 # No islands (should not happen if input is valid)\n return 1 if self.hasArticulationPoint else 2\n\n\n\n\n\n\n#https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/submissions/1349894985/\n\n```\n```Go []\nfunc minDays(grid [][]int) int {\n type Point struct {\n row, col int\n }\n \n directions := []Point{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}\n rows, cols := len(grid), len(grid[0])\n discoveryTime := make([][]int, rows)\n lowestReachableTime := make([][]int, rows)\n for i := range discoveryTime {\n discoveryTime[i] = make([]int, cols)\n lowestReachableTime[i] = make([]int, cols)\n }\n \n var time, totalLandCells int\n var hasArticulationPoint bool\n \n isValidCell := func(row, col int) bool {\n return row >= 0 && col >= 0 && row < rows && col < cols && grid[row][col] == 1\n }\n \n var dfs func(row, col, parentRow, parentCol int)\n dfs = func(row, col, parentRow, parentCol int) {\n time++\n discoveryTime[row][col] = time\n lowestReachableTime[row][col] = time\n totalLandCells++\n children := 0\n \n for _, dir := range directions {\n newRow, newCol := row+dir.row, col+dir.col\n if !isValidCell(newRow, newCol) {\n continue\n }\n \n if discoveryTime[newRow][newCol] == 0 {\n children++\n dfs(newRow, newCol, row, col)\n lowestReachableTime[row][col] = min(lowestReachableTime[row][col], lowestReachableTime[newRow][newCol])\n \n if lowestReachableTime[newRow][newCol] >= discoveryTime[row][col] && parentRow != -1 {\n hasArticulationPoint = true\n }\n } else if (newRow != parentRow || newCol != parentCol) && discoveryTime[newRow][newCol] < discoveryTime[row][col] {\n lowestReachableTime[row][col] = min(lowestReachableTime[row][col], discoveryTime[newRow][newCol])\n }\n }\n \n if parentRow == -1 && children > 1 {\n hasArticulationPoint = true\n }\n }\n \n islands := 0\n for row := 0; row < rows; row++ {\n for col := 0; col < cols; col++ {\n if grid[row][col] == 1 && discoveryTime[row][col] == 0 {\n islands++\n if islands > 1 {\n return 0 // More than one island\n }\n dfs(row, col, -1, -1)\n }\n }\n }\n \n if totalLandCells == 0 {\n return 0 // No land\n }\n if totalLandCells == 1 {\n return 1 // Only one land cell\n }\n if islands == 0 {\n return 0 // No islands (should not happen if input is valid)\n }\n if hasArticulationPoint {\n return 1\n }\n return 2\n}\n\nfunc min(a, b int) int {\n if a < b {\n return a\n }\n return b\n}\n\n\n\n\n\n//https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/submissions/1349895578/\n```\n```Rust []\nimpl Solution {\n pub fn min_days(grid: Vec<Vec<i32>>) -> i32 {\n let (rows, cols) = (grid.len(), grid[0].len());\n let mut discovery_time = vec![vec![0; cols]; rows];\n let mut lowest_reachable_time = vec![vec![0; cols]; rows];\n let mut time = 1;\n let mut has_articulation_point = false;\n let mut total_land_cells = 0;\n let directions = [(0, 1), (1, 0), (0, -1), (-1, 0)];\n \n fn is_valid_cell(row: i32, col: i32, grid: &Vec<Vec<i32>>) -> bool {\n row >= 0 && col >= 0 && (row as usize) < grid.len() && (col as usize) < grid[0].len() && grid[row as usize][col as usize] == 1\n }\n \n fn dfs(row: i32, col: i32, parent_row: i32, parent_col: i32, grid: &Vec<Vec<i32>>, \n discovery_time: &mut Vec<Vec<i32>>, lowest_reachable_time: &mut Vec<Vec<i32>>, \n time: &mut i32, has_articulation_point: &mut bool, total_land_cells: &mut i32) {\n discovery_time[row as usize][col as usize] = *time;\n lowest_reachable_time[row as usize][col as usize] = *time;\n *time += 1;\n *total_land_cells += 1;\n let mut children = 0;\n \n for &(dr, dc) in &[(0, 1), (1, 0), (0, -1), (-1, 0)] {\n let new_row = row + dr;\n let new_col = col + dc;\n \n if !is_valid_cell(new_row, new_col, grid) {\n continue;\n }\n \n if discovery_time[new_row as usize][new_col as usize] == 0 {\n children += 1;\n dfs(new_row, new_col, row, col, grid, discovery_time, lowest_reachable_time, time, has_articulation_point, total_land_cells);\n lowest_reachable_time[row as usize][col as usize] = lowest_reachable_time[row as usize][col as usize].min(lowest_reachable_time[new_row as usize][new_col as usize]);\n \n if lowest_reachable_time[new_row as usize][new_col as usize] >= discovery_time[row as usize][col as usize] && parent_row != -1 {\n *has_articulation_point = true;\n }\n } else if (new_row != parent_row || new_col != parent_col) && discovery_time[new_row as usize][new_col as usize] < discovery_time[row as usize][col as usize] {\n lowest_reachable_time[row as usize][col as usize] = lowest_reachable_time[row as usize][col as usize].min(discovery_time[new_row as usize][new_col as usize]);\n }\n }\n \n if parent_row == -1 && children > 1 {\n *has_articulation_point = true;\n }\n }\n \n let mut islands = 0;\n for row in 0..rows {\n for col in 0..cols {\n if grid[row][col] == 1 && discovery_time[row][col] == 0 {\n islands += 1;\n if islands > 1 {\n return 0; // More than one island\n }\n dfs(row as i32, col as i32, -1, -1, &grid, &mut discovery_time, &mut lowest_reachable_time, &mut time, &mut has_articulation_point, &mut total_land_cells);\n }\n }\n }\n \n if total_land_cells == 0 {\n return 0; // No land\n }\n if total_land_cells == 1 {\n return 1; // Only one land cell\n }\n if islands == 0 {\n return 0; // No islands (should not happen if input is valid)\n }\n if has_articulation_point {\n 1\n } else {\n 2\n }\n }\n}\n\n\n\n\n//https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/submissions/1349896058/\n```\n```JavaScript []\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minDays = function(grid) {\n const rows = grid.length, cols = grid[0].length;\n const discoveryTime = Array.from({length: rows}, () => new Array(cols).fill(0));\n const lowestReachableTime = Array.from({length: rows}, () => new Array(cols).fill(0));\n let time = 1;\n let hasArticulationPoint = false;\n let totalLandCells = 0;\n const DIRECTIONS = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n\n const isValidCell = (row, col) => {\n return row >= 0 && col >= 0 && row < rows && col < cols && grid[row][col] === 1;\n };\n\n const dfs = (row, col, parentRow, parentCol) => {\n discoveryTime[row][col] = time;\n lowestReachableTime[row][col] = time;\n time++;\n totalLandCells++;\n let children = 0;\n\n for (const [dx, dy] of DIRECTIONS) {\n const newRow = row + dx;\n const newCol = col + dy;\n\n if (!isValidCell(newRow, newCol)) {\n continue;\n }\n\n if (discoveryTime[newRow][newCol] === 0) {\n children++;\n dfs(newRow, newCol, row, col);\n lowestReachableTime[row][col] = Math.min(lowestReachableTime[row][col], lowestReachableTime[newRow][newCol]);\n\n if (lowestReachableTime[newRow][newCol] >= discoveryTime[row][col] && parentRow !== -1) {\n hasArticulationPoint = true;\n }\n } else if ((newRow !== parentRow || newCol !== parentCol) && discoveryTime[newRow][newCol] < discoveryTime[row][col]) {\n lowestReachableTime[row][col] = Math.min(lowestReachableTime[row][col], discoveryTime[newRow][newCol]);\n }\n }\n\n if (parentRow === -1 && children > 1) {\n hasArticulationPoint = true;\n }\n };\n\n let islands = 0;\n for (let row = 0; row < rows; row++) {\n for (let col = 0; col < cols; col++) {\n if (grid[row][col] === 1 && discoveryTime[row][col] === 0) {\n islands++;\n if (islands > 1) return 0; // More than one island\n dfs(row, col, -1, -1);\n }\n }\n }\n\n if (totalLandCells === 0) return 0; // No land\n if (totalLandCells === 1) return 1; // Only one land cell\n if (islands === 0) return 0; // No islands (should not happen if input is valid)\n\n return hasArticulationPoint ? 1 : 2;\n};\n\n\n\n//https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/submissions/1349898385/\n```\n\n\n---\n### BFS\n\n```Java []\nimport java.util.*;\n\nclass Solution {\n private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n \n public int minDays(int[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n int landCount = 0;\n \n // Count land cells\n for (int[] row : grid) {\n for (int cell : row) {\n if (cell == 1) landCount++;\n }\n }\n \n // Check initial state\n if (landCount == 0 || isDisconnected(grid)) return 0;\n if (landCount == 1) return 1;\n \n // Try removing each land cell\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (isDisconnected(grid)) return 1;\n grid[i][j] = 1;\n }\n }\n }\n \n return 2;\n }\n \n private boolean isDisconnected(int[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n boolean[][] visited = new boolean[rows][cols];\n int count = 0;\n \n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n if (count > 0) return true; // More than one island\n bfs(grid, i, j, visited);\n count++;\n }\n }\n }\n \n return count != 1; // Disconnected if no island or more than one island\n }\n \n private void bfs(int[][] grid, int startRow, int startCol, boolean[][] visited) {\n int rows = grid.length, cols = grid[0].length;\n Queue<int[]> queue = new LinkedList<>();\n queue.offer(new int[]{startRow, startCol});\n visited[startRow][startCol] = true;\n \n while (!queue.isEmpty()) {\n int[] current = queue.poll();\n \n for (int[] dir : DIRECTIONS) {\n int newRow = current[0] + dir[0];\n int newCol = current[1] + dir[1];\n \n if (isValid(grid, newRow, newCol) && !visited[newRow][newCol]) {\n queue.offer(new int[]{newRow, newCol});\n visited[newRow][newCol] = true;\n }\n }\n }\n }\n \n private boolean isValid(int[][] grid, int row, int col) {\n return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1;\n }\n}\n```\n```C++ []\n\n```\n```Python []\n\n```\n```Go []\n\n```\n```Rust []\n\n```\n```JavaScript []\n\n```\n\n### Union Find\n\n```Java []\nclass Solution {\n private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n \n public int minDays(int[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n UnionFind uf = new UnionFind(rows * cols);\n int landCount = 0;\n \n // Initialize Union-Find\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n landCount++;\n int current = i * cols + j;\n uf.addLand();\n for (int[] dir : DIRECTIONS) {\n int ni = i + dir[0], nj = j + dir[1];\n if (isValid(grid, ni, nj)) {\n int neighbor = ni * cols + nj;\n uf.union(current, neighbor);\n }\n }\n }\n }\n }\n \n // Check initial state\n if (landCount == 0 || uf.getCount() > 1) return 0;\n if (landCount == 1) return 1;\n \n // Check if removing any land cell disconnects the island\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n uf.reset();\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (grid[r][c] == 1 && (r != i || c != j)) {\n int current = r * cols + c;\n uf.addLand();\n for (int[] dir : DIRECTIONS) {\n int nr = r + dir[0], nc = c + dir[1];\n if (isValid(grid, nr, nc) && (nr != i || nc != j)) {\n int neighbor = nr * cols + nc;\n uf.union(current, neighbor);\n }\n }\n }\n }\n }\n if (uf.getCount() != 1) return 1;\n }\n }\n }\n \n return 2;\n }\n \n private boolean isValid(int[][] grid, int row, int col) {\n return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1;\n }\n \n class UnionFind {\n private int[] parent;\n private int[] rank;\n private int count;\n private final int size;\n \n public UnionFind(int n) {\n parent = new int[n];\n rank = new int[n];\n size = n;\n reset();\n }\n \n public void reset() {\n for (int i = 0; i < size; i++) {\n parent[i] = i;\n rank[i] = 0;\n }\n count = 0;\n }\n \n public int find(int x) {\n if (parent[x] != x) {\n parent[x] = find(parent[x]);\n }\n return parent[x];\n }\n \n public void union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n if (rank[rootX] < rank[rootY]) {\n parent[rootX] = rootY;\n } else if (rank[rootX] > rank[rootY]) {\n parent[rootY] = rootX;\n } else {\n parent[rootY] = rootX;\n rank[rootX]++;\n }\n count--;\n }\n }\n \n public void addLand() {\n count++;\n }\n \n public int getCount() {\n return count;\n }\n }\n}\n```\n```C++ []\n\n```\n```Python []\n\n```\n```Go []\n\n```\n```Rust []\n\n```\n```JavaScript []\n\n```\n\n\n | 2 | 1 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript'] | 1 |
minimum-number-of-days-to-disconnect-island | Minimum Number of Days to Disconnect Island - JAVA | minimum-number-of-days-to-disconnect-isl-d2xr | Intuition\n Describe your first thoughts on how to solve this problem. \nDFS , Matrix - Flip\n\n\n# Complexity\n- Time complexity: O ( m * n )\n Add your time c | Shyam2626 | NORMAL | 2024-01-07T07:41:01.465211+00:00 | 2024-01-07T07:41:01.465242+00:00 | 247 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDFS , Matrix - Flip\n\n\n# Complexity\n- Time complexity: O ( m * n )\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O ( m * n )\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minDays(int[][] grid) {\n \n int m=grid.length,n=grid[0].length;\n boolean visited[][]=new boolean[m][n];\n int islandCount=0;\n\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n if(grid[i][j]==1 && !visited[i][j]){\n islandCount++;\n countIsland(i,j,grid,visited,m,n);\n }\n\n if(islandCount > 1)\n return 0;\n\n int onesCount=0;\n\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(grid[i][j] == 1){\n onesCount++;\n grid[i][j] = 0;\n if(checkIsland(grid) > 1)\n return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n return (onesCount == 0) ? 0 :(onesCount == 1) ? 1 : 2;\n\n }\n public int checkIsland(int[][] grid){\n int islandCount=0;\n int m=grid.length,n=grid[0].length;\n boolean visited[][]=new boolean[m][n];\n\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n if(grid[i][j]==1 && !visited[i][j]){\n islandCount++;\n countIsland(i,j,grid,visited,m,n);\n }\n\n return islandCount;\n\n }\n\n public void countIsland(int r,int c,int[][] grid,boolean[][] visited,int m,int n){\n\n visited[r][c]=true;\n int arr1[]={ 0, 0, -1, 1 };\n int arr2[]={ 1, -1, 0, 0 };\n\n for(int i=0;i<4;i++){\n int nr = r + arr1[i];\n int nc = c + arr2[i];\n if(nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 1 && !visited[nr][nc])\n countIsland(nr,nc,grid,visited,m,n);\n }\n }\n}\n``` | 2 | 0 | ['Depth-First Search', 'Matrix', 'Java'] | 1 |
minimum-number-of-days-to-disconnect-island | Simple Dfs||C++||Easy | simple-dfsceasy-by-aayushi_kukreja-hxdy | \n\n# Code\n\nclass Solution {\npublic:\n void dfs(int row,int col,vector<vector<int>>& grid,vector<vector<int>>&vis)\n {\n int n = grid.size();\n | Aayushi_Kukreja | NORMAL | 2023-02-27T18:27:57.715859+00:00 | 2023-02-27T18:27:57.715899+00:00 | 182 | false | \n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int row,int col,vector<vector<int>>& grid,vector<vector<int>>&vis)\n {\n int n = grid.size();\n int m = grid[0].size();\n vis[row][col]=1;\n int delrow[] = {1, -1, 0, 0};\n int delcol[] = {0, 0, 1, -1};\n\n for(int i=0;i<4;i++)\n {\n int nrow=row+delrow[i];\n int ncol=col+delcol[i];\n\nif(nrow>=0&&nrow<n&&ncol>=0&&ncol<m&&!vis[nrow][ncol]&&grid[nrow][ncol]==1)\n {\n dfs(nrow,ncol,grid,vis);\n }\n }\n }\n int countIsland(vector<vector<int>>& grid)\n { \n int n=grid.size();\n int m=grid[0].size();\n int island=0;\n vector<vector<int>>vis(n,vector<int>(m,0));\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(!vis[i][j] && grid[i][j]==1)\n {\n dfs(i,j,grid,vis);\n island++;\n }\n }\n }\n return island;\n }\n int minDays(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n int islands=countIsland(grid);\n //all zero\n if (islands > 1 or islands == 0)\n {\n return 0;\n }\n else\n {\n\t\t\t// check for 1 ans\n for (int i = 0 ; i < n; i ++)\n {\n for (int j = 0; j < m; j++)\n {\n if (grid[i][j])\n {\n grid[i][j] = 0;\n\t\t\t\t\t\t// remove this block\n islands = countIsland(grid);\n\t\t\t\t\t\t// add back the block\n grid[i][j] = 1;\n if (islands > 1 or islands == 0)\n return 1;\n }\n\n }\n }\n }\n\t\t// else\n return 2;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Tarjan's algorithm: O(m * n) with approach and detailed comments 💯 | tarjans-algorithm-om-n-with-approach-and-4ajh | Intuition\n Describe your first thoughts on how to solve this problem. \nThe DFS function uses Tarjan\'s algorithm to identify the articulation points in the gr | abdulahadsiddiqui11 | NORMAL | 2022-12-26T05:47:41.136869+00:00 | 2022-12-26T05:47:41.136909+00:00 | 197 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe DFS function uses Tarjan\'s algorithm to identify the articulation points in the grid. It keeps track of the insertion time and lowest time of each cell, which are used to determine whether a cell is an articulation point. The insertion time of a cell is the time at which it is visited during the DFS, and the lowest time of a cell is the minimum of its insertion time and the insertion times of its neighbours that can be reached without going through the parent of the current cell.\n\nIf the lowest time of a neighbour is greater than or equal to the insertion time of the current cell, and the current cell is not the root (has a parent), it means that the neighbour can only be reached through the current cell, so if the current cell is removed, the neighbour becomes disconnected from the rest of the grid. Therefore, the current cell is an articulation point.\n\nIf the current cell has more than 1 child component and is the root (has no parent), it means that it has more than 1 neighbour that can be reached without going through the parent, so if the current cell is removed, more than 1 component becomes disconnected from the rest of the grid. Therefore, the current cell is also an articulation point.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Perform a depth-first search (DFS) on the grid to identify the articulation points. An articulation point is a cell that, when removed, disconnects the grid.\n\n\n3. If the number of connected components in the grid is not 1, the grid is already disconnected, so return 0 days. Otherwise, if the grid contains an articulation point or if there is only 1 land cell in the grid, return 1 day. Otherwise, return 2 days.\n\n# Complexity\n- Time complexity: $$O(m * n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m * n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nprivate:\n // helper function to check if the given row and column indices are within the bounds of the grid\n bool isInBounds(int row, int col, int totalRows, int totalCols) {\n return row >= 0 && row < totalRows && col >= 0 && col < totalCols;\n }\n\n // Depth-First Search function to identify the articulation points in the grid\n // An articulation point is a cell that, when removed, disconnects the grid\n void dfsArticulationPoint(int row, int col, int parentRow, int parentCol, vector<vector<int>>& insertionTime, vector<vector<int>>& lowestTime, bool& containsArticulationPoint, int& timer,\n vector<vector<bool>>& visited, vector<vector<int>>& grid, vector<int>& dRow, vector<int>& dCol) {\n // mark the current cell as visited\n visited[row][col] = true;\n\n // set the insertion time and lowest time of the current cell as the current timer value\n insertionTime[row][col] = lowestTime[row][col] = timer++;\n \n // variable to store the number of child components (connected 1s) of the current cell\n int childComponents = 0;\n\n // iterate through the 4 directions (left, right, up, down) to visit the neighbours\n for(int direction = 0; direction < 4; direction++) {\n int neighbourRow = row + dRow[direction];\n int neighbourCol = col + dCol[direction];\n\n // skip the parent cell, as it is not a neighbour\n if(neighbourRow == parentRow && neighbourCol == parentCol) continue;\n\n // if the neighbour cell is within the bounds of the grid and is a land cell (has a value of 1)\n if(isInBounds(neighbourRow, neighbourCol, grid.size(), grid[0].size()) && grid[neighbourRow][neighbourCol] == 1) {\n \n // if the neighbour has not been visited yet\n if(!visited[neighbourRow][neighbourCol]) {\n \n // recursively call the DFS function on the neighbour\n dfsArticulationPoint(neighbourRow, neighbourCol, row, col, insertionTime, lowestTime, containsArticulationPoint, timer, visited, grid, dRow, dCol);\n\n // update the lowest time of the current cell with the minimum of its current lowest time and the lowest time of the neighbour\n lowestTime[row][col] = min(lowestTime[row][col], lowestTime[neighbourRow][neighbourCol]);\n\n // if the lowest time of the neighbour is greater than or equal to the insertion time of the current cell, and the current cell is not the root (has a parent)\n if(lowestTime[neighbourRow][neighbourCol] >= insertionTime[row][col] && parentRow != -1 && parentCol != -1) {\n \n // mark that the grid contains an articulation point\n containsArticulationPoint = true;\n }\n \n // increment the number of child components of the current cell\n childComponents++;\n } else {\n // if the neighbour has already been visited, update the lowest time of the current cell \n // with the minimum of its current lowest time and the insertion time of the neighbour\n lowestTime[row][col] = min(lowestTime[row][col], insertionTime[neighbourRow][neighbourCol]);\n }\n }\n }\n\n // if the current cell has more than 1 child component and is the root (has no parent), mark that the grid contains an articulation point\n if(childComponents > 1 && parentRow == -1 && parentCol == -1) {\n containsArticulationPoint = true;\n }\n }\n\npublic:\n int minDays(vector<vector<int>>& grid) {\n // get the number of rows and columns in the grid\n int rows = grid.size();\n int cols = grid[0].size();\n\n // 2D vector to store the visited status of each cell\n vector<vector<bool>> visited(rows, vector<bool>(cols, false));\n \n // 2D vectors to store the insertion time and lowest time of each cell\n vector<vector<int>> insertionTime(rows, vector<int>(cols));\n vector<vector<int>> lowestTime(rows, vector<int>(cols));\n // variable to store whether the grid contains an articulation point\n bool containsArticulationPoint = false;\n // variable to store the timer value (incremented each time a cell is visited)\n int timer = 0;\n\n // vectors to store the row and column offsets to visit the neighbours in the 4 directions (left, right, up, down)\n vector<int> dRow = {-1, 0, 1, 0};\n vector<int> dCol = {0, 1, 0, -1};\n\n // variable to store the number of land cells (cells with a value of 1) in the grid\n int numberOfLandCells = 0;\n // variable to store the number of connected components (groups of connected 1s) in the grid\n int numberOfComponents = 0;\n\n // iterate through the grid to identify the articulation points and count the number of land cells and connected components\n for(int row = 0; row < rows; row++) {\n for(int col = 0; col < cols; col++) {\n // if the current cell is a land cell\n if(grid[row][col] == 1) {\n // increment the number of land cells\n numberOfLandCells++;\n\n // if the current cell has not been visited yet\n if(!visited[row][col]) {\n // perform DFS starting from the current cell to identify the articulation points and count the connected components\n dfsArticulationPoint(row, col, -1, -1, insertionTime, lowestTime, containsArticulationPoint, timer, visited, grid, dRow, dCol);\n \n // increment the number of connected components\n numberOfComponents++;\n }\n }\n }\n }\n\n // if the number of connected components is not 1, the grid is already disconnected, so return 0 days\n // otherwise, if the grid contains an articulation point or if there is only 1 land cell in the grid, return 1 day\n // otherwise, return 2 days\n return numberOfComponents != 1 ? 0 : containsArticulationPoint || numberOfLandCells == 1 ? 1 : 2;\n }\n};\n``` | 2 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | [C++] | The Only Observation to Solve the Problem | c-the-only-observation-to-solve-the-prob-sure | You will need at most 2 days.\n\nProof: you can always just isolate the 1 in the corner by making his 2 neighbours equal to zero.\n\nSo, first we will check the | makhonya | NORMAL | 2022-06-11T12:35:49.804473+00:00 | 2022-06-11T12:35:49.804511+00:00 | 223 | false | `You will need at most 2 days.`\n\nProof: you can always just isolate the ```1``` in the corner by making his 2 neighbours equal to zero.\n\nSo, first we will check the number of islands we have, if it is more than 1 we return 0, because islands are already disconnected. If it is equal to 1, we will replace each of 1\'s in grid to see if we can create 2 disconnected islands. And if we were not able to divide the island, we return 2.\n\n```\nclass Solution {\npublic:\n int n, m, ones = 0;\n vector<int> DIR = {1, 0, -1, 0, 1};\n int islands(vector<vector<int>>& grid){ \n vector<vector<int>> A(grid.begin(), grid.end());\n int count = 0;\n for(int i = 0; i < n; i++)\n for(int j = 0; j < m; j++)\n if(A[i][j])\n helper(i, j, A), count++;\n return count;\n }\n void helper(int i, int j, vector<vector<int>>& A){\n if(i < 0 || i == n || j < 0 || j == m || !A[i][j])\n return;\n A[i][j] = 0;\n for(int k = 0; k < 4; k++)\n helper(i + DIR[k], j + DIR[k + 1], A);\n }\n int minDays(vector<vector<int>>& grid) {\n n = grid.size(), m = grid[0].size();\n for(int i = 0; i < n; i++)\n for(int j = 0; j < m; j++)\n ones += grid[i][j];\n if(islands(grid) > 1) return 0;\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n if(grid[i][j]){\n grid[i][j] = 0;\n if(islands(grid) > 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n return min(2, ones);\n }\n};\n``` | 2 | 0 | ['Depth-First Search', 'C', 'C++'] | 1 |
minimum-number-of-days-to-disconnect-island | C++ | Similar to Finding Articulation Point | Explained | c-similar-to-finding-articulation-point-e640x | I\'ll tell you the steps:\n1) Convert the grid into a graph.\n2) If there is only one 1, then you need to remove it (because connected definition says only 1 is | harshnadar23 | NORMAL | 2021-09-15T08:46:04.470890+00:00 | 2021-09-15T08:46:04.470924+00:00 | 635 | false | I\'ll tell you the steps:\n1) Convert the grid into a graph.\n2) If there is only one 1, then you need to remove it (because connected definition says only 1 island)\n3) Find number of connected components\n4) If connected components>1 return 0\n5) Find articulation point\n6) If articulation point is present, then return 1, else return 2\nFor the code part of articulation point, you can refer to any youtube tutorial or cp algorithms\n```\nclass Solution {\npublic:\n vector<int> adj[904];\n vector<int> v;\n vector<int> vis;\n vector<int> in,low;\n int n, m;\n int timer;\n \n void dfsArticulation(int node, int par){\n vis[node] = true;\n in[node] = low[node] = timer++;\n int children=0;\n for (int it : adj[node]) {\n if (it == par) continue;\n if (vis[it]) {\n low[node] = min(low[node], in[it]);\n } else {\n dfsArticulation(it, node);\n low[node] = min(low[node], low[it]);\n if (low[it] >= in[node] && par!=-1)\n v.push_back(node);\n ++children;\n }\n }\n if(par == -1 && children > 1)\n v.push_back(node);\n }\n \n void dfs(int i){\n vis[i]=true;\n for(auto it: adj[i]){\n if(!vis[it]) dfs(it);\n }\n }\n int minDays(vector<vector<int>>& grid) {\n n=grid.size();\n m=grid[0].size();\n int dx[]={1,0,0,-1};\n int dy[]={0,1,-1,0};\n int l=1;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1) {grid[i][j]=l,l++;}\n }\n }\n if(l==2) return 1;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n for(int k=0;k<4;k++){\n int nx=i+dx[k];\n int ny=j+dy[k];\n if(nx<0 || ny<0 || nx>=n || ny>=m) continue;\n if(grid[i][j] && grid[nx][ny]){\n adj[grid[i][j]].push_back(grid[nx][ny]);\n }\n }\n }\n }\n \n vis.resize(l,false);\n int c=0;\n for(int i=1;i<l;i++){\n if(vis[i]==false){\n dfs(i);\n c++;\n }\n }\n if(c>1 || c==0) return 0;\n \n for(int i=0;i<l;i++){\n vis[i]=false;\n }\n in.resize(l,-1);\n low.resize(l,-1);\n \n for (int i = 1; i < l; ++i) {\n \n if (!vis[i])\n dfsArticulation (i,-1);\n }\n \n if(v.size()>0) return 1;\n return 2;\n }\n};\n``` | 2 | 1 | ['Depth-First Search', 'C'] | 0 |
minimum-number-of-days-to-disconnect-island | JAVA DFS(Connected Components) With Comments | java-dfsconnected-components-with-commen-xv6g | \nclass Solution {\n static int [][]dirs={{-1,0},{0,1},{0,-1},{1,0}};\n public void connectedComponents(int[][] grid, int i, int j, boolean[][] visited) { | abhirajsinha | NORMAL | 2021-08-16T06:18:26.060514+00:00 | 2021-08-16T15:12:02.804280+00:00 | 448 | false | ```\nclass Solution {\n static int [][]dirs={{-1,0},{0,1},{0,-1},{1,0}};\n public void connectedComponents(int[][] grid, int i, int j, boolean[][] visited) {\n \n visited[i][j] = true;\n for(int d=0;d<4;d++){\n int r=i+dirs[d][0];\n int c=j+dirs[d][1];\n \n if(r>=0 && r<grid.length && c>=0 && c<grid[0].length && grid[r][c]==1 && visited[r][c]==false){\n connectedComponents(grid,r,c,visited);\n }\n }\n }\n\n public int numIslands(int[][] grid) {\n int islandCount = 0;\n boolean vis[][] = new boolean[grid.length][grid[0].length];\n\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 1 && vis[i][j] == false) {\n islandCount++;\n connectedComponents(grid, i, j, vis);\n }\n }\n }\n\n return islandCount;\n }\n\n public int minDays(int[][] grid) {\n int n = grid.length;\n int m = grid[0].length;\n\n //if more than 1 island is there then the graph is already disconnected\n if (numIslands(grid) > 1) {\n return 0;\n }\n\n //check for all 1\'s remove it and if there is more than 1 island then return 1\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n\n if (numIslands(grid) != 1) {\n return 1;\n }\n\n //recorrect it while backtracking\n grid[i][j] = 1;\n }\n }\n }\n\n //else we need min 2 removal\n return 2;\n }\n}\n``` | 2 | 1 | ['Depth-First Search', 'Java'] | 2 |
minimum-number-of-days-to-disconnect-island | Java | Easy | DFS | Using Number of Islands | java-easy-dfs-using-number-of-islands-by-065d | \nclass Solution {\n public int minDays(int[][] grid) {\n int n = grid.length ;\n int m = grid[0].length ;\n if(numIslands(grid) != 1){\ | user8540kj | NORMAL | 2021-08-05T13:01:24.194275+00:00 | 2021-08-05T13:01:24.194307+00:00 | 202 | false | ```\nclass Solution {\n public int minDays(int[][] grid) {\n int n = grid.length ;\n int m = grid[0].length ;\n if(numIslands(grid) != 1){\n return 0;\n }\n for(int i = 0; i < n;i++ ){\n for(int j = 0 ; j < m ; j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n \n if(numIslands(grid) != 1){\n return 1;\n }\n \n grid[i][j] = 1;\n }\n }\n }\n return 2;\n }\n public int numIslands(int[][] grid) {\n int count = 0;\n boolean visited[][] = new boolean[grid.length][grid[0].length];\n \n for(int i = 0;i < grid.length;i++){\n for(int j = 0;j < grid[0].length;j++){\n if(grid[i][j] != 0 && visited[i][j] == false){\n \n count++;\n countIslands(grid,i,j,visited);\n }\n }\n }\n return count;\n }\n private void countIslands(int grid[][],int i,int j,boolean visited[][]){\n if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == 0 || visited[i][j] == true){\n return; \n } \n visited[i][j] = true;\n countIslands(grid,i - 1,j,visited);\n countIslands(grid,i + 1,j,visited);\n countIslands(grid,i,j - 1,visited);\n countIslands(grid,i,j + 1,visited);\n \n \n }\n}\n``` | 2 | 0 | [] | 0 |
minimum-number-of-days-to-disconnect-island | BFS C++ Approach | bfs-c-approach-by-codes_aman-nsj5 | \nclass Solution {\npublic:\n int dx[4]={-1,0,1,0};\n int dy[4]={0,1,0,-1};\n bool safe(int x,int y,int m,int n)\n {\n return (x>=0&&x<m&&y>= | codes_aman | NORMAL | 2020-11-28T13:30:36.520036+00:00 | 2020-11-28T13:30:36.520065+00:00 | 338 | false | ```\nclass Solution {\npublic:\n int dx[4]={-1,0,1,0};\n int dy[4]={0,1,0,-1};\n bool safe(int x,int y,int m,int n)\n {\n return (x>=0&&x<m&&y>=0&&y<n);\n }\n void travel(int i,int j,vector<vector<int> > &grid,vector<vector<int> > &visited)\n {\n int m=grid.size();\n int n=grid[0].size();\n queue<pair<int,int > >q;\n q.push({i,j});\n visited[i][j]=1;\n while(!q.empty())\n {\n auto p=q.front();\n q.pop();\n int x=p.first;\n int y=p.second;\n for(int k=0;k<4;k++)\n {\n int nx=x+dx[k];\n int ny=y+dy[k];\n \n if(safe(nx,ny,m,n)&&!visited[nx][ny]&&grid[nx][ny]==1)\n {\n visited[nx][ny]=1;\n q.push({nx,ny});\n }\n }\n }\n return ;\n }\n int bfs(vector<vector<int> > &grid)\n {\n //number of connected component\n int count=0;\n int m=grid.size();\n if(m==0)\n return 0;\n int n=grid[0].size();\n vector<vector<int> > visited(m,vector<int> (n,0));\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(grid[i][j]==1&&!visited[i][j])\n {\n count++;\n travel(i,j,grid,visited);\n }\n }\n }\n \n return count;\n }\n int minDays(vector<vector<int>>& grid) {\n int count=bfs(grid);\n if(count!=1)\n return 0;\n \n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[i].size();j++)\n {\n if(grid[i][j]==1)\n {\n grid[i][j]=0;\n \n count=bfs(grid);\n if(count!=1)\n return 1;\n \n grid[i][j]=1;\n }\n }\n }\n \n return 2;\n }\n};\n``` | 2 | 0 | ['Breadth-First Search', 'C'] | 1 |
minimum-number-of-days-to-disconnect-island | Easy C++ solution, with full explanation | easy-c-solution-with-full-explanation-by-shop | Connected Components\nLook closely, the answer of the question can not be greater than 2.\n\nAlgo:\n1. First Check if the connected components are already great | hiteshgupta | NORMAL | 2020-08-30T04:13:16.635256+00:00 | 2020-08-30T04:13:58.922717+00:00 | 302 | false | # Connected Components\n**Look closely, the answer of the question can not be greater than 2.**\n\nAlgo:\n1. First Check if the connected components are already greater than 1, if yes return 0\n2. Then do the following:\n for every grid value of 1, set it up for 0, check connected components, if connect components are now > 1 return ans 1, else set it up for 1 again\n3. if ans is not returned till now, ans must be 2, so just return 2 ;)\n\n\n\n```\nclass Solution {\npublic:\n \n int connected_components(vector<vector<int>>& grid)\n {\n int n=grid.size();\n if(n==0) return 0;\n int m=grid[0].size();\n \n vector<vector<bool>> vis(n,vector<bool>(m,false));\n int count=0;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(grid[i][j]==1 && vis[i][j]==false)\n {\n count++;\n queue<pair<int,int>>q;\n vis[i][j]=true;\n q.push(make_pair(i,j));\n int dir[]={0,1,0,-1,0};\n while(!q.empty())\n {\n auto p= q.front();\n q.pop();\n int x=p.first, y=p.second;\n for(int k=0;k<4;k++)\n {\n int nx= x+dir[k];\n int ny= y+dir[k+1];\n if(nx>=0 && nx<n && ny>=0 && ny<m && grid[nx][ny] && !vis[nx][ny])\n {\n vis[nx][ny]=true;\n q.push(make_pair(nx,ny));\n }\n }\n }\n }\n }\n }\n return count;\n \n }\n \n int minDays(vector<vector<int>>& grid) {\n int conn= connected_components(grid);\n if(conn>1) return 0;\n\t\t\n int n=grid.size();\n if(n==0) return 0;\n int m=grid[0].size();\n\t\t\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(grid[i][j]==1)\n {\n grid[i][j]=0;\n conn= connected_components(grid);\n if(conn>1) return 1;\n grid[i][j]=1;\n }\n }\n }\n return 2;\n }\n};\n``` | 2 | 0 | ['Breadth-First Search', 'Graph', 'C'] | 2 |
minimum-number-of-days-to-disconnect-island | C# | c-by-adchoudhary-sgjr | Code | adchoudhary | NORMAL | 2025-03-08T03:19:06.783071+00:00 | 2025-03-08T03:19:06.783071+00:00 | 2 | false | # Code
```csharp []
public class Solution {
public int MinDays(int[][] grid)
{
// Step 1: Check if the grid is already disconnected.
if (CountIslands(grid) != 1)
{
return 0;
}
// Step 2: Check for bridge-like cells.
int rows = grid.Length;
int cols = grid[0].Length;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (grid[i][j] == 1)
{
// Remove this land temporarily
grid[i][j] = 0;
if (CountIslands(grid) != 1)
{
return 1;
}
// Restore the land
grid[i][j] = 1;
}
}
}
// Step 3: If no bridge-like cell exists, return 2.
return 2;
}
private int CountIslands(int[][] grid)
{
int rows = grid.Length;
int cols = grid[0].Length;
bool[,] visited = new bool[rows, cols];
int islandCount = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (grid[i][j] == 1 && !visited[i, j])
{
islandCount++;
DFS(grid, visited, i, j);
}
}
}
return islandCount;
}
private void DFS(int[][] grid, bool[,] visited, int i, int j)
{
int[] dx = { -1, 1, 0, 0 };
int[] dy = { 0, 0, -1, 1 };
visited[i, j] = true;
for (int k = 0; k < 4; k++)
{
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >= 0 && newX < grid.Length && newY >= 0 && newY < grid[0].Length &&
grid[newX][newY] == 1 && !visited[newX, newY])
{
DFS(grid, visited, newX, newY);
}
}
}
}
``` | 1 | 0 | ['C#'] | 0 |
minimum-number-of-days-to-disconnect-island | Using Tarjan's Algorithm(if only one component) | using-tarjans-algorithmif-only-one-compo-oe2j | Intuition \n1. If there are no islands or more than 1 island, than the answer is 0, as we don\'t need to remove anything.\n2. If we can disconnct the island by | keshavchauhan107 | NORMAL | 2024-08-12T08:33:27.788330+00:00 | 2024-08-12T08:33:27.788357+00:00 | 5 | false | # Intuition \n1. If there are no islands or more than 1 island, than the answer is 0, as we don\'t need to remove anything.\n2. If we can disconnct the island by removing exactly 1 cell, the answer is 1 (will be finding Articulation point using Tarjan\'s Algorithm).\n3. At last, we can always disconnect an island by removing exactly 2 cells.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n*m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n*m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public:\n int t=0;\n void dfs_traversal(unordered_map<int,list<int>> &adj,unordered_map<int,bool> &vis,unordered_map<int,int> &low,unordered_map<int,int> &time,int node,int parent,int &c){\n t++;\n low[node]=t;\n time[node]=t;\n vis[node]=1;\n int child=0;\n for(auto it:adj[node]){\n if(it==parent) continue;\n if(!vis[it]){\n dfs_traversal(adj,vis,low,time,it,node,c);\n low[node]=min(low[node],low[it]);\n \n if(low[it]>=time[node] && parent!=-1){\n c++;\n }\n child++;\n }\n else{\n low[node]=min(low[node],time[it]);\n }\n }\n if(child>1 && parent==-1){\n c++;\n }\n }\n void dfs(vector<vector<int>> &grid,vector<vector<int>> &vis,int r,int c,int n,int m){\n int row[]={-1,0,1,0};\n int col[]={0,1,0,-1};\n vis[r][c]=1;\n for(int i=0;i<4;i++){\n int r1=r+row[i];\n int c1=c+col[i];\n if(r1>=0 && r1<n && c1>=0 && c1<m && grid[r1][c1]){\n if(!vis[r1][c1]){\n dfs(grid,vis,r1,c1,n,m);\n } \n }\n }\n }\npublic:\n int minDays(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n int count=0;\n vector<vector<int>> vis(n,vector<int> (m,0));\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j] && !vis[i][j]){\n dfs(grid,vis,i,j,n,m);\n count++;\n }\n }\n }\n if(count==0 || count>1){\n return 0;\n }\n else if(count==1){\n int node=-1;\n unordered_map<int,list<int>> adj;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]){\n if(node==-1){\n node=i*m+j;\n }\n int row[]={-1,0,1,0};\n int col[]={0,1,0,-1};\n for(int k=0;k<4;k++){\n int r1=i+row[k];\n int c1=j+col[k];\n if(r1>=0 && r1<n && c1>=0 && c1<m && grid[r1][c1]){\n adj[i*m+j].push_back(r1*m+c1);\n }\n }\n }\n }\n }\n unordered_map<int,int> time;\n unordered_map<int,int> low;\n unordered_map<int,bool> vis;\n int c=0;\n dfs_traversal(adj,vis,low,time,node,-1,c);\n\n if(adj.size()==1){\n return 1;\n }\n if(c>0 && adj.size()!=2){\n return 1;\n }\n }\n return 2;\n }\n};\n``` | 1 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'Strongly Connected Component', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | C++,DFS | cdfs-by-daredreamer-7stk | Intuition\njust try to count diagonal one connected to one single source\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nDFS\n Desc | daredreamer | NORMAL | 2024-08-11T20:12:36.004778+00:00 | 2024-08-11T20:12:36.004797+00:00 | 23 | false | > # Intuition\njust try to count diagonal one connected to one single source\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDFS\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // Function to count the number of islands\n int countIslands(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int count = 0;\n \n vector<vector<int>> visited(n, vector<int>(m, 0));\n \n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < m; ++j) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n dfs(grid, visited, i, j);\n count++;\n }\n }\n }\n return count;\n }\n \n // Depth-First Search to mark all connected lands\n void dfs(vector<vector<int>>& grid, vector<vector<int>>& visited, int i, int j) {\n int n = grid.size();\n int m = grid[0].size();\n if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0 || visited[i][j]) {\n return;\n }\n visited[i][j] = 1;\n dfs(grid, visited, i + 1, j);\n dfs(grid, visited, i - 1, j);\n dfs(grid, visited, i, j + 1);\n dfs(grid, visited, i, j - 1);\n }\n \n int minDays(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n \n // Step 1: Check if the grid is already disconnected\n if (countIslands(grid) != 1) {\n return 0;\n }\n \n // Step 2: Try removing each land cell to see if it disconnects the grid\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < m; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (countIslands(grid) != 1) {\n return 1;\n }\n grid[i][j] = 1;\n }\n }\n }\n \n // Step 3: If removing one cell doesn\'t work, try removing two cells\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < m; ++j) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n for (int x = 0; x < n; ++x) {\n for (int y = 0; y < m; ++y) {\n if (grid[x][y] == 1) {\n grid[x][y] = 0;\n if (countIslands(grid) != 1) {\n return 2;\n }\n grid[x][y] = 1;\n }\n }\n }\n grid[i][j] = 1;\n }\n }\n }\n \n // By this logic, we would always return within the loop,\n // but if not, it would take 2 days at most to disconnect the grid.\n return 2;\n }\n};\n\n``` | 1 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Simple Logic, Just observe and dry run few test cases | simple-logic-just-observe-and-dry-run-fe-kf4p | Intuition\n1. If Initial number of Islands are greater than 1 or equal to zero return 0.\n2. Now change one by one each 1 to 0, count the number of new islands | Hardy1 | NORMAL | 2024-08-11T19:31:30.676454+00:00 | 2024-08-11T19:31:30.676491+00:00 | 25 | false | # Intuition\n1. If Initial number of Islands are greater than 1 or equal to zero return 0.\n2. Now change one by one each 1 to 0, count the number of new islands and replace 0 with 1. If new islands greater than 1 or equal to 0 then return 1.\n3. In the worst case like this [[1,1,1],[1,1,1],[1,1,1]] here you can see changing (1,2) and (2,1) is the only way to form 2 islands, so in the worst case minimum number of days will be 2. \n\n# Approach\n1. DFS for looking for Islands.\n2. Count function for counting Islands.\n\n# Complexity\n- Time complexity:\nO(N*M)\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int i, int j, vector<vector<int>>& grid) {\n grid[i][j] = 0; // Mark the current cell as visited (0 = water)\n int x[4] = {0, -1, 0, 1};\n int y[4] = {-1, 0, 1, 0};\n for (int k = 0; k < 4; k++) {\n int nr = i + x[k];\n int nc = j + y[k];\n if (nr >= 0 && nc >= 0 && nr < grid.size() && nc < grid[0].size() && grid[nr][nc] == 1) {\n dfs(nr, nc, grid);\n }\n }\n }\n\n int countIslands(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n int count = 0;\n vector<vector<int>> gridCopy = grid;\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (gridCopy[i][j] == 1) {\n count++;\n dfs(i, j, gridCopy);\n }\n }\n }\n\n return count;\n }\n\n int minDays(vector<vector<int>>& grid) {\n int initialIslands = countIslands(grid);\n\n if (initialIslands > 1 || initialIslands == 0) {\n return 0;\n }\n\n // Check if removing one land cell creates multiple islands\n for (int i = 0; i < grid.size(); i++) {\n for (int j = 0; j < grid[0].size(); j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0; // Remove the land cell\n int newIslands = countIslands(grid);\n grid[i][j] = 1; // Restore the land cell\n\n if (newIslands > 1 || newIslands==0) {\n return 1; // We can create more than one island by removing this cell\n }\n }\n }\n }\n\n // If removing one land cell doesn\'t create multiple islands, return 2\n return 2;\n }\n};\n\n``` | 1 | 0 | ['Depth-First Search', 'Matrix', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Simple Explanation | simple-explanation-by-aayushbharti-n74h | Intuition\nTo disconnect an island, you need to break the connectivity of the land cells. This can be done by either removing a single land cell or, if the isla | AayushBharti | NORMAL | 2024-08-11T18:44:35.251315+00:00 | 2024-08-11T18:44:35.251344+00:00 | 17 | false | # Intuition\nTo disconnect an island, you need to break the connectivity of the land cells. This can be done by either removing a single land cell or, if the island is very connected, you might need to remove two or more. The minimum number of days is determined by the number of cells that need to be removed to disconnect the grid.\n\n# Approach\n1. **Check Initial Connectivity**: First, check if the grid is already disconnected. If there is more than one island, return 0.\n2. **Single Day Removal**: Try to disconnect the grid by removing any single land cell (changing 1 to 0) and check if the grid becomes disconnected. If so, return 1.\n3. **Double Day Removal**: If removing a single cell doesn\'t disconnect the island, check if removing two cells can disconnect the island. If yes, return 2.\n4. If none of the above work, return 2 since the maximum number of days required to disconnect any grid is 2.\n\n# Complexity\n- Time complexity: \\(O(m \\times n \\times (m \\times n))\\) for checking connectivity after removing each land cell.\n- Space complexity: \\(O(m \\times n)\\) for storing visited cells during DFS.\n\n# Code\n```java\nclass Solution {\n public int minDays(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n\n // Check if the grid is already disconnected\n if (numOfIslands(grid) != 1) return 0;\n\n // Try to disconnect by removing one cell\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (numOfIslands(grid) != 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n // If one cell removal doesn\'t work, two cells must be enough\n return 2;\n }\n\n private int numOfIslands(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n boolean[][] visited = new boolean[m][n];\n int count = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n count++;\n if (count > 1) return count;\n dfs(grid, i, j, visited);\n }\n }\n }\n return count;\n }\n\n private void dfs(int[][] grid, int i, int j, boolean[][] visited) {\n int m = grid.length, n = grid[0].length;\n if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0 || visited[i][j]) return;\n visited[i][j] = true;\n dfs(grid, i - 1, j, visited);\n dfs(grid, i + 1, j, visited);\n dfs(grid, i, j - 1, visited);\n dfs(grid, i, j + 1, visited);\n }\n}\n | 1 | 0 | ['Java'] | 0 |
minimum-number-of-days-to-disconnect-island | C# Beats 100% with 113 ms | c-beats-100-with-113-ms-by-zocolini-mazy | Intuition\nFirst we can prove that the maximun number of days needed is 2. We also can prove that for islands of 1, 2 or 3 lands we already know the number o da | zocolini | NORMAL | 2024-08-11T17:25:01.572232+00:00 | 2024-08-11T17:25:01.572266+00:00 | 11 | false | # Intuition\nFirst we can prove that the maximun number of days needed is 2. We also can prove that for islands of 1, 2 or 3 lands we already know the number o days needed.\n\n# Approach\nWe first check the number os 1s to discard those cases that we already know how they end. Next step it\'s try to find one bridge point using brute force. If we find it we know that with one day it\'s enough. In a different case we return 2, the max number of days needed as we proved.\n\n# Complexity\n- Time complexity: *O(n * m)*\n\n- Space complexity: *O(n * m)*\n\n# Code\n```\npublic class Solution {\n public int MinDays(int[][] grid)\n {\n var lands = 0;\n if (CountIslands(grid, ref lands) != 1) return 0;\n\n if (lands == 1) return 1;\n if (lands == 2) return 2;\n if (lands == 3) return 1;\n\n if (BruteForce(grid)) return 1;\n\n return 2;\n }\n\n // Brute force nested for loop to iterate the grid searching for a bridge node.\n private static bool BruteForce(int[][] grid)\n {\n for (int i = 0; i < grid.Length; i++)\n {\n for (int j = 0; j < grid[0].Length; j++)\n {\n if (grid[i][j] == 0) continue;\n \n grid[i][j] = 0;\n if (CountIslands(grid) != 1) return true;\n\n grid[i][j] = 1;\n }\n }\n\n return false;\n }\n\n // Same as the function below but this time we add one parameter that\'s counting the the number of 1s in the grid.\n private static int CountIslands(int[][] grid, ref int lands)\n {\n var visited = new bool[grid.Length, grid[0].Length];\n var count = 0;\n\n for (int i = 0; i < grid.Length; i++)\n {\n for (int j = 0; j < grid[0].Length; j++)\n {\n if (grid[i][j] != 1) continue;\n\n if (visited[i, j]) continue;\n\n VisitCells(i, j, ref lands);\n count++;\n }\n }\n\n return count;\n\n void VisitCells(int i, int j, ref int lands)\n {\n if (grid[i][j] == 0) return;\n if (visited[i, j]) return;\n\n visited[i, j] = true;\n lands++;\n\n if (i > 0) VisitCells(i - 1, j, ref lands);\n\n if (i < grid.Length - 1) VisitCells(i + 1, j, ref lands);\n\n if (j > 0) VisitCells(i, j - 1, ref lands);\n\n if (j < grid[0].Length - 1) VisitCells(i, j + 1, ref lands);\n }\n }\n \n\n // Counting the islands adding 1 to the count when we start a new VisitCell() loop. We use an array to mark the already visited lands.\n private static int CountIslands(int[][] grid)\n {\n var visited = new bool[grid.Length, grid[0].Length];\n var count = 0;\n\n for (int i = 0; i < grid.Length; i++)\n {\n for (int j = 0; j < grid[0].Length; j++)\n {\n if (grid[i][j] != 1) continue;\n\n if (visited[i, j]) continue;\n\n VisitCells(i, j);\n count++;\n }\n }\n\n return count;\n\n void VisitCells(int i, int j)\n {\n if (grid[i][j] == 0) return;\n if (visited[i, j]) return;\n\n visited[i, j] = true;\n\n if (i > 0) VisitCells(i - 1, j);\n\n if (i < grid.Length - 1) VisitCells(i + 1, j);\n\n if (j > 0) VisitCells(i, j - 1);\n\n if (j < grid[0].Length - 1) VisitCells(i, j + 1);\n }\n }\n}\n``` | 1 | 0 | ['C#'] | 0 |
minimum-number-of-days-to-disconnect-island | ✨[TYPESCRIPT]✨ 140 ms Beats 79.37% ✅ | typescript-140-ms-beats-7937-by-rain84-nxpl | Intuition\n\nThere is a lot of LOC\'s, but it is not a most complicated solution.\nRealy. \n\n# Approach\n\n1. Use dfs and use it to count the number of "island | rain84 | NORMAL | 2024-08-11T17:18:29.327404+00:00 | 2024-08-13T08:04:22.301155+00:00 | 30 | false | # Intuition\n\nThere is a lot of LOC\'s, but it is not a most complicated solution.\nRealy. \n\n# Approach\n\n1. Use dfs and use it to count the number of "islands"\n2. If there are 0 islands or more than the 1st, it means that nothing in the matrix needs to be changed and we return a zero\n3. Go through the "island" cells of the matrix and see how many islands there will be if the cell becomes "water"\n\n# Code\n```\nfunction minDays(grid: number[][]): number {\n const [m, n] = [grid.length, grid[0].length]\n\n const dfs = (i: number, j: number) => {\n if (i < 0 || m <= i || j < 0 || n <= j || [0, 2].includes(grid[i][j])) return\n\n grid[i][j] = 2\n const dir = [-1, 0, 1, 0, -1]\n for (let k = 0; k < 4; k++) {\n const [y, x] = [i + dir[k], j + dir[k + 1]]\n dfs(y, x)\n }\n }\n\n const count = () => {\n let c = 0\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1) {\n dfs(i, j)\n c++\n }\n }\n }\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 2) {\n grid[i][j] = 1\n }\n }\n }\n\n return c\n }\n\n if (count() !== 1) return 0\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0\n\n if (count() !== 1) return 1\n\n grid[i][j] = 1\n }\n }\n }\n\n return 2\n}\n```\n\n## **Please upvote \uD83D\uDC4D if you like \u2764\uFE0F my solution** | 1 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Matrix', 'TypeScript', 'JavaScript'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy to understand C++ solution with comments. | easy-to-understand-c-solution-with-comme-tivb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | BhavyaGautam899 | NORMAL | 2024-08-11T17:10:54.143429+00:00 | 2024-08-11T17:10:54.143461+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int row,int col,vector<vector<int>>&grid,vector<vector<int>> &vis,int m,int n){\n\n if(row<0 || row>=m || col<0 || col>=n || vis[row][col]==1 || grid[row][col]==0){\n return;\n }\n vis[row][col]=1;\n\n int delR[]={-1,0,1,0};\n int delC[]={0,1,0,-1};\n for(int i=0;i<4;i++){\n int nrow = row+delR[i];\n int ncol = col+delC[i];\n dfs(nrow,ncol,grid,vis,m,n);\n }\n }\n int minDays(vector<vector<int>>& grid) {\n //The first thing that we would like to do here is that we would like to count the number of islands by doing a dfs.\n int m=grid.size();\n int n=grid[0].size();\n vector<vector<int>> vis(m,vector<int>(n,0));\n int count=0;\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j]==1 && vis[i][j]==0){\n dfs(i,j,grid,vis,m,n); \n count++;\n }\n }\n }\n // cout<<count;\n\n //if the count of the island is 0 or greater that one than we do not need to make any removal so we return 0;\n if(count!=1)return 0;\n \n //if that is not the case then we try to convert every land cell into water and then try to find the number of island \n //and then find the number of islands again using the above approach.\n \n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n // if the current cell is a land then set it to water and again calculate the number of islands. \n if(grid[i][j]==1)\n {\n //set it to zero.\n grid[i][j]=0;\n //and re-evaluate the number of islands.\n int num = 0;\n //a visited vector to keep track of visited cells.\n vector<vector<int>> vis1(m,vector<int>(n,0));\n for(int row=0;row<m;row++)\n {\n for(int col=0;col<n;col++)\n {\n if(grid[row][col]==1 && vis1[row][col]==0)\n {\n dfs(row,col,grid,vis1,m,n); \n num++;\n }\n }\n }\n // If after converting one cell to water we get our number of island from 1 to 0 or greater than 1 we will return \n // 1 as our answer as it took us 1 removal. If that is not the case then it will surely take us 2 removal. We can\n // say this by applying elemination. Since the answer will never be more than 2. \n // Why the answer will be atmost 2??.\n // No matter how many land cell we have we only need to isolate on land cell to convert one island into 2. \n // To isolate 1 land cell we need at-max two removal. Because no matter the number of land cells we have there will\n // always be a cell that is connected to land from only two side. If we remove those two side we can disconnect. \n \n if(num!=1)\n {\n return 1;\n }\n grid[i][j]=1;//set it back to 1.\n \n }\n }\n }\n return 2;\n }\n};\n``` | 1 | 0 | ['Depth-First Search', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | solution -python | solution-python-by-shrutisingh64-unmb | Intuition\nThe grid consists of 1s (land) and 0s (water)\nThe goal is to find the minimum number of days required to disconnect the island, meaning that no two | shrutisingh64 | NORMAL | 2024-08-11T16:17:54.587525+00:00 | 2024-08-11T16:17:54.587558+00:00 | 48 | false | # Intuition\nThe grid consists of 1s (land) and 0s (water)\nThe goal is to find the minimum number of days required to disconnect the island, meaning that no two 1s are connected.\nIn one day, you can remove one 1 (land cell) from the grid.\nAfter removing a 1, the grid is updated, and the remaining 1s may become disconnected.\nThe process continues until the island is completely disconnected.\n# Approach\nCount the number of islands in the grid.\nIf there are multiple islands, return 0 (no need to disconnect).\nTemporarily remove the island by setting all land cells to 0.\nCount the number of islands again.\nIf there are multiple islands after removal, return 1 (removing one land cell can disconnect the island).\nIf there are no islands after removal, return 2 (removing two land cells is required to disconnect the island).\n\nThe code uses a recursive Depth-First Search (DFS) approach to:\nCount the number of islands (_count_islands function)\nExplore the island and mark its cells as visited (_explore_island function)\n\n\n# Complexity\n- Time complexity:\nO(r*c)\n\n- Space complexity:\nO(r*c)\n\n# Code\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n\n def _count_islands():\n visited = set()\n count = 0\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1 and (i, j) not in visited:\n _explore_island(i, j, visited)\n count += 1\n return count\n\n def _explore_island(i, j, visited):\n if (\n i < 0\n or i >= rows\n or j < 0\n or j >= cols\n or grid[i][j] == 0\n or (i, j) in visited\n ):\n return\n visited.add((i, j))\n for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n _explore_island(i + di, j + dj, visited)\n\n if _count_islands() != 1:\n return 0\n\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n grid[i][j] = 0\n if _count_islands() != 1:\n return 1\n grid[i][j] = 1\n\n return 2\n``` | 1 | 0 | ['Python3'] | 0 |
minimum-number-of-days-to-disconnect-island | C++ Approach || Time complexity O(m*n)^2 & space complexity O(m&n) || Simple Dfs Approach | c-approach-time-complexity-omn2-space-co-a3j6 | Complexity\n- Time complexity:O(mn)^2\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(mn)\n Add your space complexity here, e.g. O(n) \n\n# | sneha029 | NORMAL | 2024-08-11T16:15:52.227596+00:00 | 2024-08-11T16:15:52.227625+00:00 | 35 | false | # Complexity\n- Time complexity:O(m*n)^2\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int m, n;\n void dfs(vector<vector<int>>& grid, int i, int j, vector<vector<bool>>& vis){\n if(i<0 || i>=m || j<0 || j>=n || vis[i][j]==true || grid[i][j]==0) return;\n\n vis[i][j] = true;\n\n\n dfs(grid, i+1, j, vis);\n dfs(grid, i-1, j, vis);\n dfs(grid, i, j+1, vis);\n dfs(grid, i, j-1, vis);\n\n }\n int countNoOfIslandUtil(vector<vector<int>>& grid){\n vector<vector<bool>> vis(m, vector<bool>(n, false));\n int island = 0;\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(grid[i][j]==1 && vis[i][j]==false){\n island++;\n dfs(grid, i, j, vis);\n }\n }\n }\n\n return island;\n }\n int minDays(vector<vector<int>>& grid) {\n\n m = grid.size();\n n = grid[0].size();\n\n int islands = countNoOfIslandUtil(grid);\n\n if(islands>1 || islands==0) return 0;\n\n else {\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(grid[i][j]==1){\n grid[i][j] = 0;\n int noOfIsland = countNoOfIslandUtil(grid);\n if(noOfIsland>1 || noOfIsland==0) return 1;\n grid[i][j]=1; \n }\n }\n }\n }\n\n return 2;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | 🧠✅ PYTHON SIMPLE SOLUTION EXPLAINED IN DETAILS ✔️🔥🧠 | python-simple-solution-explained-in-deta-wgln | \n## Intuition \uD83E\uDD14\nThe key to solving this problem is to understand that we need to find the minimum number of days required to disconnect the grid, w | sagarsaini_ | NORMAL | 2024-08-11T14:08:07.972986+00:00 | 2024-08-11T14:08:07.973020+00:00 | 12 | false | \n## Intuition \uD83E\uDD14\nThe key to solving this problem is to understand that we need to find the minimum number of days required to disconnect the grid, which means we need to find the minimum number of cells that, when changed from land to water, will result in the grid having more than one island or no islands at all.\n\nTo achieve this, we can use a depth-first search (DFS) approach to count the number of islands in the grid. If the grid is already disconnected (i.e., has more than one island), we can return 0 as the minimum number of days required. Otherwise, we need to check each land cell individually to see if changing it to water will disconnect the grid.\n\n## Approach \uD83D\uDCDD\n1. **Define a helper function** `helper(grid, m, n, vis)` that takes the grid, its dimensions (m x n), and a visited array `vis` as input. This function will perform DFS to count the number of islands in the grid.\n\n2. **Inside the `helper` function**, define a nested function `dfs(row, col, vis, grid, m, n)` that performs the depth-first search. It marks the current cell as visited and recursively calls `dfs` on its neighboring land cells (up, down, left, right).\n\n3. **In the `helper` function**, iterate through the grid and call `dfs` on each unvisited land cell. Keep track of the number of islands (`connect_cnt`).\n\n4. **If `connect_cnt` is 0 or greater than 1**, return `True`, indicating that the grid is already disconnected or can be disconnected by changing a single cell.\n\n5. **If `connect_cnt` is exactly 1**, return `False`, indicating that the grid is currently connected.\n\n6. **In the main function**, create a temporary grid `temp` to store the visited cells.\n\n7. **If `helper(grid, m, n, temp)` returns `True`**, it means the grid is already disconnected, so return 0.\n\n8. **Iterate through each cell in the grid**. If the current cell is land (1), change it to water (0) temporarily.\n\n9. **Call `helper(grid, m, n, temp)` with the modified grid**. If it returns `True`, it means changing this cell to water disconnects the grid, so return 1.\n\n10. **If no single cell change disconnects the grid**, it means we need to change two cells to disconnect the grid. Return 2.\n\n## Example \uD83C\uDF04\nLet\'s consider the following example grid:\n\n```\ngrid = [\n [1, 1, 0, 0, 0],\n [0, 1, 0, 0, 1],\n [0, 0, 0, 1, 1],\n [0, 0, 0, 0, 0],\n [0, 0, 1, 1, 0]\n]\n```\n\nIn this grid, we have two islands initially. Therefore, the minimum number of days required to disconnect the grid is 0.\n\nHowever, let\'s assume we have the following grid:\n\n```\ngrid = [\n [1, 1, 0, 0, 0],\n [0, 1, 0, 0, 1],\n [0, 0, 0, 1, 1],\n [0, 0, 0, 0, 1],\n [0, 0, 1, 1, 0]\n]\n```\n\nIn this case, changing the cell at (3, 4) from land to water will disconnect the grid. Therefore, the minimum number of days required is 1.\n\n## Simulation \uD83C\uDFA2\nLet\'s simulate the execution of the code step by step for the second example grid:\n\n1. **Create a temporary grid `temp` to store the visited cells.**\n2. **Call `helper(grid, m, n, temp)`.**\n - **Inside `helper`**, call `dfs(0, 0, vis, grid, m, n)` and `dfs(0, 1, vis, grid, m, n)`. The `connect_cnt` becomes 1.\n - **Return `False` from `helper`** since `connect_cnt` is exactly 1.\n3. **Iterate through each cell in the grid.**\n4. **For the cell at (0, 0)**, change it to water temporarily and call `helper(grid, m, n, temp)`.\n - **Inside `helper`**, call `dfs(0, 1, vis, grid, m, n)` and `dfs(1, 0, vis, grid, m, n)`. The `connect_cnt` becomes 2.\n - **Return `True` from `helper`** since `connect_cnt` is greater than 1.\n5. **Return 1 from the main function** since changing a single cell disconnects the grid.\n\n## Time Complexity (TC) \uD83D\uDD70\uFE0F\nThe time complexity of this solution is O(m * n), where m and n are the dimensions of the grid. This is because we iterate through each cell in the grid and perform a DFS operation on each unvisited land cell. The DFS operation visits each cell at most once.\n\n## Space Complexity (SC) \uD83E\uDDE0\nThe space complexity is O(m * n) due to the temporary grid `temp` used to store the visited cells during the DFS operation. Additionally, the recursive calls in the DFS function may consume O(m * n) space in the worst case scenario (e.g., when the grid is a single island).\n\n\n# Code\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n def helper(grid, m, n, vis):\n # Depth-first search function\n def dfs(row, col, vis, grid, m, n):\n vis[row][col] = 1 # Mark current cell as visited\n delr = [0, 1, 0, -1] # Row directions\n dcol = [1, 0, -1, 0] # Column directions\n for i in range(4):\n nr = row + delr[i]\n nc = col + dcol[i]\n # Check if neighbor is within grid bounds and is an unvisited land cell\n if (nr >= 0 and nr < m and nc >= 0 and nc < n) and (vis[nr][nc] == 0 and grid[nr][nc] == 1):\n dfs(nr, nc, vis, grid, m, n) # Recursively call DFS on neighbor\n \n connect_cnt = 0\n for i in range(m):\n for j in range(n):\n # If current cell is an unvisited land cell, perform DFS\n if vis[i][j] == 0 and grid[i][j] == 1:\n dfs(i, j, vis, grid, m, n)\n connect_cnt += 1\n \n # If there are 0 or more than 1 islands, return True (disconnected)\n if connect_cnt == 0 or connect_cnt > 1:\n return True\n else:\n return False\n \n # Create a temporary visited grid\n temp = [[0 for _ in range(n)] for i in range(m)]\n \n # If the grid is already disconnected, return 0\n if helper(grid, m, n, temp):\n return 0\n \n # Iterate through each cell in the grid\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n # Create a new temporary visited grid for each cell\n temp = [[0 for _ in range(n)] for i in range(m)]\n \n # Change the current cell to water temporarily\n grid[i][j] = 0\n \n # If changing the current cell disconnects the grid, return 1\n if helper(grid, m, n, temp):\n return 1\n \n # Restore the current cell to land\n grid[i][j] = 1\n \n # If no single cell change disconnects the grid, return 2\n return 2\n \n```\n\n\nIn conclusion, this solution efficiently finds the minimum number of days required to disconnect the grid by performing a depth-first search and checking each land cell individually. The intuition, approach, examples, simulations, TC, and SC provide a comprehensive understanding of the problem and the solution. \uD83C\uDF89\uD83C\uDF89\uD83C\uDF89\n\n---\n\n\n | 1 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'Strongly Connected Component', 'Python3'] | 0 |
minimum-number-of-days-to-disconnect-island | Easy solution | Step by Step Detailed Full Solution | C++ Solution | easy-solution-step-by-step-detailed-full-j8xl | For the full code, check at bottom. \n### Problem Understanding:\nYou have a grid where each cell is either land (1) or water (0). The goal is to determine the | aizagazyani16 | NORMAL | 2024-08-11T13:38:59.921533+00:00 | 2024-08-11T13:38:59.921561+00:00 | 17 | false | > # For the full code, check at bottom. \n### Problem Understanding:\nYou have a grid where each cell is either land (1) or water (0). The goal is to determine the minimum number of days needed to disconnect an island in the grid. An island is defined as a group of connected land cells (horizontally or vertically). \n\nYou need to:\n1. Check if the grid is already disconnected (i.e., has more than one island).\n2. Try removing each land cell one by one to see if that makes the grid disconnected.\n3. If removing one cell doesn\'t work, it will take at least two days to disconnect the grid.\n\n### Code Breakdown:\n\n#### 1. Main Function: `minDays`\nThis is the function that coordinates the solution.\n\n```cpp\nint minDays(vector<vector<int>>& grid) {\n int rows = grid.size();\n int cols = grid[0].size();\n int initialIslandCount = countIslands(grid);\n\n if (initialIslandCount != 1) {\n return 0;\n }\n\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (grid[row][col] == 0) continue;\n\n grid[row][col] = 0;\n int newIslandCount = countIslands(grid);\n\n if (newIslandCount != 1) return 1;\n\n grid[row][col] = 1;\n }\n }\n\n return 2;\n}\n```\n\n- **Initial Setup**:\n - `rows` and `cols` store the number of rows and columns in the grid.\n - `initialIslandCount` gets the number of islands in the initial grid using the `countIslands` function.\n\n- **Check If Already Disconnected**:\n - If `initialIslandCount` is not equal to 1, it means the grid is already disconnected or there are no islands. So, return `0`.\n\n- **Try Removing Each Land Cell**:\n - Iterate through each cell in the grid.\n - If the cell is land (1), temporarily change it to water (0).\n - Recount the islands with `countIslands`.\n - If removing this cell makes the number of islands different from 1, it means the grid is disconnected with one removal. So, return `1`.\n\n- **Fallback**:\n - If no single cell removal works, return `2`, meaning it will take at least two days to disconnect the grid.\n\n#### 2. Counting Islands: `countIslands`\nThis function counts the number of islands in the grid.\n\n```cpp\nint countIslands(vector<vector<int>>& grid) {\n int rows = grid.size();\n int cols = grid[0].size();\n vector<vector<bool>> visited(rows, vector<bool>(cols, false));\n int islandCount = 0;\n\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (!visited[row][col] && grid[row][col] == 1) {\n exploreIsland(grid, row, col, visited);\n islandCount++;\n }\n }\n }\n return islandCount;\n}\n```\n\n- **Setup**:\n - `visited` is a 2D vector that keeps track of which cells have been visited.\n - `islandCount` keeps track of the number of islands found.\n\n- **Iterate Through the Grid**:\n - For each cell, if it\'s land (1) and hasn\'t been visited, start exploring this island using `exploreIsland` function and increase the `islandCount`.\n\n- **Return**:\n - Return the total count of islands found.\n\n#### 3. Exploring an Island: `exploreIsland`\nThis function marks all cells of an island as visited.\n\n```cpp\nvoid exploreIsland(vector<vector<int>>& grid, int row, int col, vector<vector<bool>>& visited) {\n visited[row][col] = true;\n\n for (const auto& direction : DIRECTIONS) {\n int newRow = row + direction[0];\n int newCol = col + direction[1];\n if (isValidLandCell(grid, newRow, newCol, visited)) {\n exploreIsland(grid, newRow, newCol, visited);\n }\n }\n}\n```\n\n- **Mark Current Cell**:\n - Mark the current cell as visited.\n\n- **Explore Adjacent Cells**:\n - Check all 4 possible directions (right, left, down, up).\n - Use `isValidLandCell` to check if the adjacent cell is valid (within bounds, land, and not visited).\n - Recursively call `exploreIsland` on valid adjacent cells.\n\n#### 4. Checking Valid Land Cell: `isValidLandCell`\nThis function checks if a cell is valid for exploration.\n\n```cpp\nbool isValidLandCell(const vector<vector<int>>& grid, int row, int col, const vector<vector<bool>>& visited) {\n int rows = grid.size();\n int cols = grid[0].size();\n return row >= 0 && col >= 0 && row < rows && col < cols &&\n grid[row][col] == 1 && !visited[row][col];\n}\n```\n\n- **Bounds and Cell Check**:\n - Ensure the cell is within grid bounds.\n - Ensure the cell is land (1) and not visited.\n\n### Summary:\n1. **Count Initial Islands**: Check if the grid is already disconnected.\n2. **Try Removing Each Cell**: Check if removing a single land cell can disconnect the grid.\n3. **Fallback**: If not possible with one cell, it takes at least two removals.\n\nBy breaking down the problem and understanding each function\u2019s role, you can better grasp how the solution works and apply similar logic to other grid-based problems.\n\n# Full code\n\n# Code\n```\nclass Solution {\nprivate:\n const vector<vector<int>> DIRECTIONS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n\npublic:\n int minDays(vector<vector<int>>& grid) {\n int rows = grid.size();\n int cols = grid[0].size();\n int initialIslandCount = countIslands(grid);\n\n if (initialIslandCount != 1) {\n return 0;\n }\n\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (grid[row][col] == 0) continue;\n\n grid[row][col] = 0;\n int newIslandCount = countIslands(grid);\n\n if (newIslandCount != 1) return 1;\n\n grid[row][col] = 1;\n }\n }\n\n return 2;\n }\n\nprivate:\n int countIslands(vector<vector<int>>& grid) {\n int rows = grid.size();\n int cols = grid[0].size();\n vector<vector<bool>> visited(rows, vector<bool>(cols, false));\n int islandCount = 0;\n\n for (int row = 0; row < rows; row++) {\n for (int col = 0; col < cols; col++) {\n if (!visited[row][col] && grid[row][col] == 1) {\n exploreIsland(grid, row, col, visited);\n islandCount++;\n }\n }\n }\n return islandCount;\n }\n\n void exploreIsland(vector<vector<int>>& grid, int row, int col, vector<vector<bool>>& visited) {\n visited[row][col] = true;\n\n for (const auto& direction : DIRECTIONS) {\n int newRow = row + direction[0];\n int newCol = col + direction[1];\n if (isValidLandCell(grid, newRow, newCol, visited)) {\n exploreIsland(grid, newRow, newCol, visited);\n }\n }\n }\n\n bool isValidLandCell(const vector<vector<int>>& grid, int row, int col, const vector<vector<bool>>& visited) {\n int rows = grid.size();\n int cols = grid[0].size();\n return row >= 0 && col >= 0 && row < rows && col < cols &&\n grid[row][col] == 1 && !visited[row][col];\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | ✅EASY JAVA SOLUTION BEATS 100% | easy-java-solution-beats-100-by-swayam28-btvi | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | swayam28 | NORMAL | 2024-08-11T13:38:46.957869+00:00 | 2024-08-11T13:38:46.957898+00:00 | 53 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int time;\n int[][] vis;\n int[][] low;\n int[] d=new int[]{0,1,0,-1,0};\n boolean arti;\n public int minDays(int[][] grid) {\n int n=grid.length;\n int m=grid[0].length;\n arti=false;\n vis=new int[n][m];\n low=new int[n][m];\n time=1;\n boolean hasArt=false;\n boolean found=false;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1){\n if(found)\n return 0;\n found=true;\n art(i,j,grid,-100,-100);\n }\n }\n }\n\n if(time==1)\n return 0;\n\n if(time==2)\n return 1;\n if(arti)\n return 1;\n else\n return 2;\n }\n\n public void art(int row,int col,int[][] grid , int parRow,int parCol){\n grid[row][col]=0;\n vis[row][col]=time;\n low[row][col]=time;\n time++;\n int child=0;\n for(int i=0;i<4;i++){\n int x=d[i]+row;\n int y=d[i+1]+col;\n\n if(x<0 || y<0 || x>=grid.length || y>=grid[0].length || (x==parRow && y==parCol) || (vis[x][y]==0 && grid[x][y]==0))\n continue;\n if(vis[x][y]==0){\n child++;\n art(x,y,grid,row,col);\n low[row][col]=Math.min(low[row][col],low[x][y]);\n if(low[x][y]>=vis[row][col] && (parRow!=-100 && parCol!=-100))\n arti=true;\n }else{\n low[row][col]=Math.min(low[row][col],vis[x][y]);\n }\n }\n\n if(parRow==-100 && parCol==-100 && child>1)\n arti=true;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-number-of-days-to-disconnect-island | DFS Brute-Force Beats 78% | dfs-brute-force-beats-78-by-robin_rathor-9wuj | \n# Code\n\nclass Solution {\n private:\n void dfs(vector<vector<int>>& temp, int i, int j){\n if(i < 0 || j < 0 || i >= temp.size() || j >= temp[i | Robin_Rathore | NORMAL | 2024-08-11T13:24:21.814288+00:00 | 2024-08-11T13:24:21.814314+00:00 | 24 | false | \n# Code\n```\nclass Solution {\n private:\n void dfs(vector<vector<int>>& temp, int i, int j){\n if(i < 0 || j < 0 || i >= temp.size() || j >= temp[i].size() || temp[i][j] == 0) return;\n\n if(temp[i][j])\n temp[i][j] = 0;\n dfs(temp, i+1, j);\n dfs(temp, i, j+1);\n dfs(temp, i-1, j);\n dfs(temp, i, j-1);\n }\npublic:\n int minDays(vector<vector<int>>& grid) {\n int cnt =0;\n vector<vector<int>> temp(grid.begin(), grid.end());\n for(int i =0; i < temp.size(); ++i){\n for(int j =0; j < temp[i].size(); ++j){\n if(temp[i][j] == 1){\n dfs(temp, i, j);\n cnt++;\n }\n }\n }\n if(cnt > 1 || cnt == 0) return 0;\n cnt =0;\n for(int i =0; i < grid.size(); ++i){\n for(int j =0; j < grid[i].size(); ++j){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n cnt =0;\n // temp.erase();\n // temp.resize(grid.begin(), grid.end());\n temp = grid;\n for(int k =0; k < temp.size(); ++k){\n for(int p =0; p < temp[k].size(); ++p){\n if(temp[k][p] == 1){\n dfs(temp, k, p);\n cnt++;\n }\n }\n }\n grid[i][j] = 1;\n if(cnt > 1 || cnt == 0) return 1;\n }\n }\n }\n return 2;\n\n\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Minimum Number of Days to Disconnect Island: Efficient DFS-Based Solution | minimum-number-of-days-to-disconnect-isl-dm0y | Intuition\nIn this problem, the goal is to determine the minimum number of days required to disconnect an island, where an island is defined as a connected grou | ruturaj_dm | NORMAL | 2024-08-11T12:52:02.575443+00:00 | 2024-08-11T12:53:35.154759+00:00 | 31 | false | # Intuition\nIn this problem, the goal is to determine the minimum number of days required to disconnect an island, where an island is defined as a connected group of land cells (1s) in a grid.\n\n# Approach:\n1. Initial Check: We first count the number of islands in the grid. If the island count is not exactly one, the grid is already disconnected, so we return 0.\n\n2. Removing Each Land Cell: We then attempt to disconnect the island by removing each land cell (1) one by one:\n\n - Temporarily set the cell to water (0).\n - Recount the number of islands. If this operation increases the number of islands, it means the grid can be disconnected by removing just one cell, and we return 1.\n - Revert the cell back to land (1) if the island count remains one.\n3. Final Result: If removing a single cell does not disconnect the island, the minimum number of days required is 2, meaning two cells need to be removed to achieve disconnection.\n\n# Key Functions:\n1. countNumberOfIslands(grid): Counts the number of islands using DFS.\n2. dfs(grid, r, c, visited): Depth-First Search to explore and mark visited cells of an island.\n\n\n# Complexity\n- Time complexity:\nO((MN)^2)\n\n- Space complexity:\nO(M*N)\n\n# Code\n```\nclass Solution {\n public int minDays(int[][] grid) {\n int islandCount = countNumberOfIslands(grid);\n if (islandCount != 1) {\n return 0;\n }\n\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[i].length; j++) {\n if (grid[i][j] == 0) {\n continue;\n }\n\n grid[i][j] = 0;\n int localCount = countNumberOfIslands(grid);\n if (localCount != 1) {\n return 1;\n }\n grid[i][j] = 1;\n }\n }\n\n return 2;\n }\n\n private int countNumberOfIslands(int[][] grid) {\n int n = grid.length;\n int m = grid[0].length;\n boolean[][] visited = new boolean[n][m];\n int count = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 0 || visited[i][j]) {\n continue;\n }\n\n dfs(grid, i, j, visited);\n count++;\n }\n }\n\n return count;\n }\n\n private void dfs(int[][] grid, int r, int c, boolean[][] visited) {\n if (r < 0 || r == grid.length || \n c < 0 || c == grid[0].length || \n grid[r][c] == 0 || visited[r][c]) {\n return;\n } \n\n visited[r][c] = true;\n int[][] dirs = {{r+1, c}, {r-1, c}, {r, c+1}, {r, c-1}};\n for (int[] dir : dirs) {\n dfs(grid, dir[0], dir[1], visited);\n }\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-number-of-days-to-disconnect-island | EASY CODE EXPLAINED || Disconnecting a Grid: Minimum Days to Disconnect Land Cells in a Matrix | easy-code-explained-disconnecting-a-grid-85dv | Problem Statement\nThe function minDays determines the minimum number of days required to disconnect a grid (represented as a 2D list) into two or more disconne | Person_UK | NORMAL | 2024-08-11T11:52:36.424717+00:00 | 2024-08-11T11:52:36.424740+00:00 | 39 | false | # Problem Statement\nThe function minDays determines the minimum number of days required to disconnect a grid (represented as a 2D list) into two or more disconnected components by removing land cells. The grid consists of land cells (represented by 1s) and water cells (represented by 0s).\n\n# Key Concepts\n**Grid Traversal:** The algorithm utilizes Depth-First Search (DFS) to traverse the grid and explore connected land components.\nDisconnection Condition: The goal is to determine if the grid can be disconnected by removing one or two land cells.\n\n# Code Walkthrough\n**1. Function Definition and Grid Dimensions**\n\n\n- rows and cols capture the dimensions of the grid.\n\n**2. Depth-First Search (DFS)**\n\n\n- **Purpose**: The dfs function is used to explore all land cells connected to the current land cell (r, c) using DFS.\n- **Base Case:** The recursion stops if:\nThe indices are out of bounds.\nThe cell is water (0).\nThe cell has already been visited.\n- **Recursive Exploration**: It marks the current cell as visited and recursively explores all four neighboring cells (right, down, left, and up).\n\n**3. Initial Component Count**\n\n\n- **Purpose**: The outer loops count the number of connected components (islands) in the grid.\n- **Initial Check**: If the grid has more than one connected component initially, the grid is already disconnected, so the function returns 0.\n\n**4. Attempt to Disconnect by Removing One Land Cell**\n\n\n- **Iterating Over Land Cells**: \n\nFor each land cell (r, c) in the grid:\nTemporarily remove the land cell by setting grid[r][c] to 0.\n\nRecompute the number of connected components.\n\nCheck Disconnection: If removing the cell causes the grid to disconnect (i.e., more than one component is found), the function returns 1.\n\nRestore the Grid: If the grid is not disconnected, the land cell is restored.\n\n**5. Conclusion: Disconnect by Removing Two Land Cells**\n\n**Return 2**: If the grid cannot be disconnected by removing one land cell, then it will require the removal of at least two land cells, so the function returns 2.\n\n# Code\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n rows , cols = len(grid), len(grid[0])\n\n def dfs(r,c, visit):\n if (r < 0 or c < 0 or r == rows or c == cols or grid[r][c] == 0 or (r, c) in visit):\n return\n visit.add((r, c))\n neighbours = [[r+1, c], [r, c+1], [r-1,c], [r, c-1]]\n for nc, nr in neighbours:\n dfs(nc, nr, visit)\n \n visit = set()\n count = 0\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] and (r, c) not in visit:\n dfs(r, c, visit)\n count += 1\n \n if count != 1:\n return 0\n \n land = list(visit)\n\n for r, c in land:\n grid[r][c] = 0\n visit = set()\n count = 0\n for r2 in range(rows):\n for c2 in range(cols):\n if grid[r2][c2] and (r2, c2) not in visit:\n dfs(r2, c2, visit)\n count += 1\n if count != 1:\n return 1\n grid[r][c] = 1\n\n return 2\n``` | 1 | 0 | ['Array', 'Depth-First Search', 'Python3'] | 0 |
minimum-number-of-days-to-disconnect-island | Ruby || DFS | ruby-dfs-by-alecn2002-w4en | \n# Code\nruby\nclass Grid\n include Enumerable\n\n attr_reader :grid, :h, :w, :hr, :wr\n\n def initialize(grid)\n @grid, @h, @w = grid, grid.si | alecn2002 | NORMAL | 2024-08-11T11:26:14.342906+00:00 | 2024-08-11T11:26:14.342931+00:00 | 10 | false | \n# Code\n```ruby\nclass Grid\n include Enumerable\n\n attr_reader :grid, :h, :w, :hr, :wr\n\n def initialize(grid)\n @grid, @h, @w = grid, grid.size, grid.first.size\n @hr, @wr = (0...h), (0...w)\n end\n\n def each\n grid.each_with_index {|row, ridx|\n row.each_with_index {|cell, cidx| yield(cell, ridx, cidx) }\n }\n end\n\n def dfs(r, c, cell = nil)\n return false if @vis.dig(r, c) || (cell || grid.dig(r, c)) != 1\n @vis[r][c] = true\n dfs(r + 1, c) if r + 1 < h\n dfs(r - 1, c) if r > 0\n dfs(r, c + 1) if c + 1 < w\n dfs(r, c - 1) if c > 0\n true\n end\n\n def count_islands\n @vis = Array.new(h) { Array.new(w, false) }\n count {|cell, ridx, cidx| dfs(ridx, cidx, cell) }\n end\n\n def solve\n return 0 unless count_islands == 1\n each {|cell, ridx, cidx|\n if cell == 1 then\n @grid[ridx][cidx] = 0\n return 1 unless count_islands == 1\n @grid[ridx][cidx] = 1\n end\n }\n 2\n end\nend\n\ndef min_days(grid) = Grid.new(grid).solve\n``` | 1 | 0 | ['Ruby'] | 0 |
minimum-number-of-days-to-disconnect-island | easy||c++||only BFS||graph||beginner friendly||striver|| | easyconly-bfsgraphbeginner-friendlystriv-j7u8 | Intuition\n Describe your first thoughts on how to solve this problem. \nyou need to get no of island problem before doing it;\nthat qsn is the prerequisite of | sidvi | NORMAL | 2024-08-11T10:46:17.670567+00:00 | 2024-08-11T10:46:17.670597+00:00 | 23 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nyou need to get no of island problem before doing it;\nthat qsn is the prerequisite of this problem\n\nlink:- https://leetcode.com/problems/number-of-islands/description/\nsolution to prerequisite problem:- https://leetcode.com/problems/number-of-islands/solutions/5621240/easy-c-bfs-beginner-graph/\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n// fun to check no of islands\nint fun(vector<vector<int>> grid){\n int n=grid.size();\n int m=grid[0].size();\n vector<vector<int>> check(n,vector<int>(m,0));\n int dr[]={0,1,-1,0};\n int dc[]={-1,0,0,1};\n int island=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(check[i][j]==0 && grid[i][j]==1){\n queue<pair<int,int>>q;\n check[i][j]=1;\n q.push(make_pair(i,j));\n while(!q.empty()){\n int x=q.front().first;\n int y=q.front().second;\n q.pop();\n for(int d=0;d<4;d++){\n int cx=x+dr[d];\n int cy=y+dc[d];\n if(cx>=0&&cy>=0&&cx<n&&cy<m&&check[cx][cy]==0&&grid[cx][cy]==1){\n check[cx][cy]=1;\n q.push(make_pair(cx,cy));\n }\n }\n }\n island++;\n }\n }\n }\n return island;\n}\n int minDays(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n int island=fun(grid);\n if(island!=1){\n return 0;\n }\n\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1){\n grid[i][j]=0;//remove the land in particular pos\n island=fun(grid);\n if(island !=1){// check if the no of island is not equal to one after removing the land in pos\n return 1;\n }\n grid[i][j]=1;//add the removed land and check once again\n }\n }\n }\n return 2;\n }\n};\n``` | 1 | 0 | ['Array', 'Breadth-First Search', 'Matrix', 'Strongly Connected Component', 'C++'] | 0 |
minimum-number-of-days-to-disconnect-island | C++ | Max 2 Removal | c-max-2-removal-by-sarvesh225-odq7 | Approach\n Describe your approach to solving the problem. \nIf there are more than 1 disconnected islands return 0.\nIf all the elements of grid are 0 return 0. | sarvesh225 | NORMAL | 2024-08-11T10:32:59.475509+00:00 | 2024-08-11T10:35:14.494387+00:00 | 3 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nIf there are more than 1 disconnected islands return 0.\nIf all the elements of grid are 0 return 0.\nOne by one change the elements of the islands to 0, one at a time and check if any conversion disconnects the island. If it does return 1, else return 2 as it can be the maximum answer where we are isolating the corner 1 disconnecting it from the island.\n\n# Complexity\n- Time complexity:O(n*m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n*m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(vector<vector<int>>& grid,int i, int j){\n if(i<0 || j<0 || i >= grid.size() || j >= grid[0].size()){\n return;\n }\n if(grid[i][j] == 0 || grid[i][j] == 2){\n return;\n }\n grid[i][j] = 2;\n dfs(grid,i+1,j);\n dfs(grid,i,j+1);\n dfs(grid,i-1,j);\n dfs(grid,i,j-1);\n }\n int check(vector<vector<int>> grid){\n int m = grid.size();\n int n = grid[0].size();\n int count = 0;\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j] == 1){\n dfs(grid,i,j);\n count++;\n }\n }\n }\n return count;\n }\n int minDays(vector<vector<int>>& grid) {\n int cnt = check(grid);\n if(cnt > 1){\n return 0;\n }\n int cntt = 0;\n int m = grid.size();\n int n = grid[0].size();\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n int temp = check(grid);\n if(temp > 1 || temp == 0){\n return 1;\n }\n grid[i][j] = 1;\n cntt++;\n }\n }\n }\n if(cntt == 0){\n return 0;\n }\n return 2;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Simple Approach Beats 78.74% in time and 97.99% in space🔥🔥 | simple-approach-beats-7874-in-time-and-9-4n0r | Intuition\nSimple bombing approach grid to get the number of islands\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach\n1)If number | pranjalkishor5 | NORMAL | 2024-08-11T09:15:15.717545+00:00 | 2024-08-11T09:15:15.717580+00:00 | 6 | false | # Intuition\nSimple bombing approach grid to get the number of islands\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n1)If number of islands is not one return 0.\n2)Try changing all one to zeros one at a time , if any of them disconnects the island return 1.\n3)Now if step 1 doesn\'t brew a result then just return 2.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void populate(vector<vector<int>>& ,int ,int );\n void make_one(vector<vector<int>>& ); \n int minDays(vector<vector<int>>& );\n int get_islands(vector<vector<int>>& );\n};\n\nvoid Solution::populate(vector<vector<int>>& grid,int i,int j){\n if (i<0 || i>=grid.size())\n return ;\n if (j<0 || j>=grid[0].size())\n return ;\n if (grid[i][j]!=1)\n return ;\n grid[i][j]=2;\n populate(grid,i-1,j);\n populate(grid,i+1,j);\n populate(grid,i,j-1);\n populate(grid,i,j+1);\n}\n\nint Solution::get_islands(vector<vector<int>>& grid){\n int count=0;\n for (int i=0;i<grid.size();i++){\n for (int j=0;j<grid[0].size();j++){\n if (grid[i][j]==1){\n count++;\n populate(grid,i,j);\n }\n }\n }\n return count;\n}\n\nvoid Solution::make_one(vector<vector<int>>& grid){\n for (int i=0;i<grid.size();i++){\n for (int j=0;j<grid[0].size();j++){\n if (grid[i][j]==2)\n grid[i][j]=1;\n }\n }\n}\n\nint Solution::minDays(vector<vector<int>>& grid){\n if (get_islands(grid)!=1)\n return 0;\n make_one(grid);\n for (int i=0;i<grid.size();i++){\n for (int j=0;j<grid[0].size();j++){\n if (grid[i][j]==1){\n grid[i][j]=0;\n if (get_islands(grid)!=1)\n return 1;\n make_one(grid);\n grid[i][j]=1;\n }\n }\n }\n return 2;\n}\n``` | 1 | 0 | ['C++'] | 0 |
minimum-number-of-days-to-disconnect-island | Simple BFS ✏️✏️✏️ | Python3 🔥🔥🔥 | simple-bfs-python3-by-lightning_mc_queen-54qv | Complexity\n- Time complexity: O(MN)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(MN)\n Add your space complexity here, e.g. O(n) \n\n# | Lightning_Mc_Queen | NORMAL | 2024-08-11T08:30:40.890867+00:00 | 2024-08-11T08:30:40.890907+00:00 | 10 | false | # Complexity\n- Time complexity: $$O(M*N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M*N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]\n def count(grid):\n islands = []\n vis = set()\n for i in range(m):\n for j in range(n):\n if grid[i][j] and (i, j) not in vis:\n vis.add((i, j))\n cur = 0\n q = [(i, j)]\n while q:\n curi, curj = q.pop(0)\n cur += 1\n for k in range(4):\n nr, nc = curi+dx[k], curj+dy[k]\n if 0<= nr< m and 0<=nc < n and grid[nr][nc] and (nr, nc) not in vis:\n vis.add((nr, nc))\n q.append((nr, nc))\n # print("added", q)\n if cur:\n islands.append(cur)\n # print(len(islands))\n return len(islands)\n\n if count(grid) != 1:\n return 0\n \n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n grid[i][j] = 0\n if count(grid) != 1:\n return 1\n grid[i][j] = 1\n return 2\n``` | 1 | 0 | ['Breadth-First Search', 'Matrix', 'Python3'] | 0 |
minimum-number-of-days-to-disconnect-island | Interview Solution || Easy to Understand || Most Optimized | interview-solution-easy-to-understand-mo-81s4 | \n\n# Complexity\n- Time complexity: O (n * m)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O (n * m)\n Add your space complexity here, e. | muntajir | NORMAL | 2024-08-11T08:07:08.202912+00:00 | 2024-08-11T08:07:08.202937+00:00 | 109 | false | \n\n# Complexity\n- Time complexity: O (n * m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O (n * m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n private final int[] delRow= {1,-1,0,0};\n private final int[] delCol= {0,0,-1,1};\n private void dfs(int[][] grid,int[][] vis, int n,int m, int row,int col)\n {\n if(row < 0 || row >= n || col < 0 || col >= m || vis[row][col] == 1 || grid[row][col] == 0)\n {\n return;\n }\n\n vis[row][col]=1;\n\n for(int i=0; i<4; i++)\n {\n int nRow= row + delRow[i];\n int nCol= col + delCol[i];\n \n if(nRow >= 0 && nRow < n && nCol >= 0 && nCol < m && grid[nRow][nCol] == 1 && vis[nRow][nCol] == 0)\n {\n dfs(grid, vis, n,m ,nRow,nCol);\n }\n\n }\n }\n\n private int Cislands(int[][] grid, int n, int m){\n \n int island = 0;\n int[][] vis= new int[n][m];\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(grid[i][j] == 1 && vis[i][j] == 0){\n island++;\n dfs(grid, vis,n, m, i, j);\n }\n }\n }\n \n return island;\n \n }\n\n public int minDays(int[][] grid) {\n \n int n = grid.length;\n int m= grid[0].length;\n int[][] vis = new int[n][m];\n\n int islands = Cislands(grid, n, m);\n \n if(islands != 1) return 0;\n\n int ans=0;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(grid[i][j] == 1){\n grid[i][j] = 0;\n int count= Cislands(grid, n, m);\n if(count != 1) return 1;\n grid[i][j]=1;\n }\n }\n }\n\n return 2;\n \n }\n}\n``` | 1 | 0 | ['Depth-First Search', 'Matrix', 'Strongly Connected Component', 'Java'] | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.