diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b92483 --- /dev/null +++ b/.gitignore @@ -0,0 +1,102 @@ +# Created by .ignore support plugin (hsz.mobi) +### Go template +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/dictionaries +.idea/**/shelf + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests +### Example user template template +### Example user template + +# IntelliJ project files +.idea +*.iml +out +gen### macOS template +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c4ab9e9 --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# leetcode-cn.com +use golang resolve problems in leetcode-cn.com + +**自己学习golang所写,可能有更简单,性能更好的可以pull requests一起学习够浪** + +> 每个源码都有简单的leetcode上所要求的测试 + +--- + +**源代码目录所对应的leetcode** + +``` +. +└── queueAstack (https://leetcode-cn.com/explore/learn/card/queue-stack/) + ├── bfs (https://leetcode-cn.com/explore/learn/card/queue-stack/217/queue-and-bfs/) + │   ├── lands (https://leetcode-cn.com/explore/learn/card/queue-stack/217/queue-and-bfs/872/) + │   ├── lock (https://leetcode-cn.com/explore/learn/card/queue-stack/217/queue-and-bfs/873/) + │   └── square (https://leetcode-cn.com/explore/learn/card/queue-stack/217/queue-and-bfs/874/) + ├── conclusion (https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/) + │   ├── decodestring (https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/890/) + │   ├── floodfill (https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/891/) + │   ├── keysArooms (https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/893/) + │   ├── matrix (https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/892/) + │   ├── queueTstack (https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/889/) + │   └── stackTqueue (https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/888/) + ├── dfs (https://leetcode-cn.com/explore/learn/card/queue-stack/219/stack-and-dfs/) + │   ├── binarytree (https://leetcode-cn.com/explore/learn/card/queue-stack/219/stack-and-dfs/887/) + │   ├── clonegraph (golang无内置gui库,暂未实现) + │   ├── lands (https://leetcode-cn.com/explore/learn/card/queue-stack/219/stack-and-dfs/883/) + │   └── targetsum (https://leetcode-cn.com/explore/learn/card/queue-stack/219/stack-and-dfs/885/) + ├── queue (https://leetcode-cn.com/explore/learn/card/queue-stack/216/queue-first-in-first-out-data-structure/865/) + └── stack (https://leetcode-cn.com/explore/learn/card/queue-stack/218/stack-last-in-first-out-data-structure/) + ├── minstack (https://leetcode-cn.com/explore/learn/card/queue-stack/218/stack-last-in-first-out-data-structure/877/) + ├── rpn (https://leetcode-cn.com/explore/learn/card/queue-stack/218/stack-last-in-first-out-data-structure/880/) + ├── temperature (https://leetcode-cn.com/explore/learn/card/queue-stack/218/stack-last-in-first-out-data-structure/879/) + └── valid (https://leetcode-cn.com/explore/learn/card/queue-stack/218/stack-last-in-first-out-data-structure/878/) +``` + + +``` +. +├── arrayAstring +├── linkedlist +└── queueAstack + +``` + diff --git a/array-and-string/198/770/pivotindex.go b/array-and-string/198/770/pivotindex.go new file mode 100644 index 0000000..e89f176 --- /dev/null +++ b/array-and-string/198/770/pivotindex.go @@ -0,0 +1,23 @@ +package pivotindex + +func pivotIndex(nums []int) int { + var sum, lsum int + + if len(nums) == 0 { + return -1 + } + + for _, v := range nums { + sum += v + } + + for i := range nums { + if lsum == sum-lsum-nums[i] { + return i + } + + lsum += nums[i] + } + + return -1 +} diff --git a/array-and-string/198/770/pivotindex_test.go b/array-and-string/198/770/pivotindex_test.go new file mode 100644 index 0000000..8a97c22 --- /dev/null +++ b/array-and-string/198/770/pivotindex_test.go @@ -0,0 +1,15 @@ +package pivotindex + +import "testing" + +func TestPivotIndex(t *testing.T) { + nums := []int{1, 7, 3, 6, 5, 6} + + expectation := 3 + + r := pivotIndex(nums) + + if r != expectation { + t.Error("find pivot index error") + } +} diff --git a/array-and-string/198/772/plusone.go b/array-and-string/198/772/plusone.go new file mode 100644 index 0000000..e2fc25f --- /dev/null +++ b/array-and-string/198/772/plusone.go @@ -0,0 +1,22 @@ +package plusone + +func plusOne(digits []int) []int { + l, tmp := len(digits), []int{} + for l > 0 { + if r := digits[l-1]; r+1 < 10 { + digits[l-1]++ + tmp = append(tmp, digits...) + break + } else { + digits[l-1] = 0 + if l == 1 { + tmp = append(tmp, 1) + tmp = append(tmp, digits...) + break + } else { + l-- + } + } + } + return tmp +} diff --git a/array-and-string/198/772/plusone_test.go b/array-and-string/198/772/plusone_test.go new file mode 100644 index 0000000..378d52f --- /dev/null +++ b/array-and-string/198/772/plusone_test.go @@ -0,0 +1,17 @@ +package plusone + +import "testing" + +func TestPlusOne(t *testing.T) { + digits := []int{1, 2, 3} + + r := plusOne(digits) + + expectation := []int{1, 2, 4} + + for i := range r { + if r[i] != expectation[i] { + t.Error("plus one error") + } + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..fb738fb --- /dev/null +++ b/go.mod @@ -0,0 +1 @@ +module leetcode-cn.com diff --git a/linked-list/193/741/designlist.go b/linked-list/193/741/designlist.go new file mode 100644 index 0000000..abfd34d --- /dev/null +++ b/linked-list/193/741/designlist.go @@ -0,0 +1,134 @@ +package designsinglylist + +type MyLinkedList struct { + val interface{} + len int + head *MyLinkedList + tail *MyLinkedList + next *MyLinkedList +} + +/** Initialize your data structure here. */ +func Constructor() MyLinkedList { + return MyLinkedList{} +} + +/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ +func (this *MyLinkedList) Get(index int) int { + if index < 0 || index >= this.len { + return -1 + } + + tmp := new(MyLinkedList) + tmp = this.head + for i := 0; i < index; i++ { + tmp = tmp.next + } + + v, ok := tmp.val.(int) + if !ok { + panic("get val error") + } + return v +} + +/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ +func (this *MyLinkedList) AddAtHead(val int) { + if this.head == nil { + this.head = this + this.tail = this + this.val = val + this.len++ + return + } + this.len++ + this.head = &MyLinkedList{ + val: val, + next: this.head, + } +} + +/** Append a node of value val to the last element of the linked list. */ +func (this *MyLinkedList) AddAtTail(val int) { + if this.tail == nil { + this.head = this + this.tail = this + this.val = val + this.len++ + return + } + this.len++ + tmp := &MyLinkedList{} + tmp.val = val + this.tail.next = tmp + this.tail = tmp +} + +/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ +func (this *MyLinkedList) AddAtIndex(index int, val int) { + if index > this.len || index < 0 { + return + } + if index == this.len { + this.AddAtTail(val) + return + } + if index == 0 { + this.AddAtHead(val) + return + } + + this.len++ + tmp := new(MyLinkedList) + tmp = this.head + for i := 0; i < index-1; i++ { + tmp = tmp.next + } + tmpcur := &MyLinkedList{} + tmpcur.val = val + tmpcur.next = tmp.next + tmp.next = tmpcur +} + +/** Delete the index-th node in the linked list, if the index is valid. */ +func (this *MyLinkedList) DeleteAtIndex(index int) { + if index < 0 || index >= this.len { + return + } + + if this.len == 1 { + this.val = nil + this.len-- + this.head = nil + this.tail = nil + this.next = nil + return + } + + // find previous node which node need to delete + tmp := new(MyLinkedList) + tmp = this.head + for i := 0; i < index-1; i++ { + tmp = tmp.next + } + + if index == this.len-1 { + this.len-- + this.tail = tmp + tmp.next = nil + return + } + + this.len-- + tmp.next = tmp.next.next +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Get(index); + * obj.AddAtHead(val); + * obj.AddAtTail(val); + * obj.AddAtIndex(index,val); + * obj.DeleteAtIndex(index); + */ diff --git a/linked-list/193/741/designlist_test.go b/linked-list/193/741/designlist_test.go new file mode 100644 index 0000000..3517cab --- /dev/null +++ b/linked-list/193/741/designlist_test.go @@ -0,0 +1,17 @@ +package designsinglylist + +import "testing" + +func TestDesignList(t *testing.T) { + lt := Constructor() + lt.AddAtHead(1) + lt.AddAtTail(3) + lt.AddAtIndex(1, 2) + r1 := lt.Get(1) + lt.DeleteAtIndex(1) + r2 := lt.Get(1) + + if r1 != 2 && r2 != 3 { + t.Error("design linked list error") + } +} diff --git a/linked-list/194/744/listcycle.go b/linked-list/194/744/listcycle.go new file mode 100644 index 0000000..efa9949 --- /dev/null +++ b/linked-list/194/744/listcycle.go @@ -0,0 +1,25 @@ +package listcycle + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func hasCycle(head *ListNode) bool { + if head == nil || head.Next == nil { + return false + } + + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + if slow == fast { + return true + } + } + + return false +} diff --git a/linked-list/194/744/listcycle_test.go b/linked-list/194/744/listcycle_test.go new file mode 100644 index 0000000..765a651 --- /dev/null +++ b/linked-list/194/744/listcycle_test.go @@ -0,0 +1,26 @@ +package listcycle + +import "testing" + +func TestListCycle(t *testing.T) { + + head := &ListNode{ + Val: 3, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 0, + Next: &ListNode{ + Val: -4, + }, + }, + }, + } + head.Next.Next.Next = head.Next + + r := hasCycle(head) + + if !r { + t.Error("has cycle error") + } +} diff --git a/linked-list/194/744/listnode.go b/linked-list/194/744/listnode.go new file mode 100644 index 0000000..8f0bdd8 --- /dev/null +++ b/linked-list/194/744/listnode.go @@ -0,0 +1,6 @@ +package listcycle + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/194/745/listcycle2.go b/linked-list/194/745/listcycle2.go new file mode 100644 index 0000000..a0aa124 --- /dev/null +++ b/linked-list/194/745/listcycle2.go @@ -0,0 +1,30 @@ +package listcycle2 + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func detectCycle(head *ListNode) *ListNode { + slow, fast := head, head + + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + + if slow == fast { + fast = head + for { + if slow == fast { + return slow + } + slow = slow.Next + fast = fast.Next + } + } + } + + return nil +} diff --git a/linked-list/194/745/listcycle2_test.go b/linked-list/194/745/listcycle2_test.go new file mode 100644 index 0000000..85c6b04 --- /dev/null +++ b/linked-list/194/745/listcycle2_test.go @@ -0,0 +1,25 @@ +package listcycle2 + +import "testing" + +func TestListCycle2(t *testing.T) { + head := &ListNode{ + Val: 3, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 0, + Next: &ListNode{ + Val: -4, + }, + }, + }, + } + head.Next.Next.Next = head.Next + + r := detectCycle(head) + + if r == head.Next { + t.Log("tail connects to node index 1") + } +} diff --git a/linked-list/194/745/listnode.go b/linked-list/194/745/listnode.go new file mode 100644 index 0000000..ef18919 --- /dev/null +++ b/linked-list/194/745/listnode.go @@ -0,0 +1,6 @@ +package listcycle2 + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/194/746/2listintersection.go b/linked-list/194/746/2listintersection.go new file mode 100644 index 0000000..0f32e18 --- /dev/null +++ b/linked-list/194/746/2listintersection.go @@ -0,0 +1,51 @@ +package twolistintersection + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func getIntersectionNode(headA, headB *ListNode) *ListNode { + + // count len of headA and headB + pointerA, pointerB := headA, headB + var lA, lB int + for pointerA != nil { + lA++ + pointerA = pointerA.Next + } + for pointerB != nil { + lB++ + pointerB = pointerB.Next + } + + pointerA, pointerB = headA, headB + if lA > lB { + for i := 0; i < lA-lB; i++ { + pointerA = pointerA.Next + } + for pointerA != nil { + if pointerA == pointerB { + return pointerA + } + pointerA = pointerA.Next + pointerB = pointerB.Next + } + return nil + } + + for i := 0; i < lB-lA; i++ { + pointerB = pointerB.Next + } + + for pointerB != nil { + if pointerA == pointerB { + return pointerB + } + pointerA = pointerA.Next + pointerB = pointerB.Next + } + return nil +} diff --git a/linked-list/194/746/2listintersection_test.go b/linked-list/194/746/2listintersection_test.go new file mode 100644 index 0000000..83386b4 --- /dev/null +++ b/linked-list/194/746/2listintersection_test.go @@ -0,0 +1,39 @@ +package twolistintersection + +import "testing" + +func Test2ListIntersection(t *testing.T) { + + intersection := &ListNode{ + Val: 8, + Next: &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 5, + }, + }, + } + headA := &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 1, + Next: intersection, + }, + } + headB := &ListNode{ + Val: 5, + Next: &ListNode{ + Val: 0, + Next: &ListNode{ + Val: 1, + Next: intersection, + }, + }, + } + + r := getIntersectionNode(headA, headB) + + if r == intersection { + t.Logf("Intersected at '%d'", r.Val) + } +} diff --git a/linked-list/194/746/listnode.go b/linked-list/194/746/listnode.go new file mode 100644 index 0000000..92c0fd7 --- /dev/null +++ b/linked-list/194/746/listnode.go @@ -0,0 +1,6 @@ +package twolistintersection + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/194/747/nodelist.go b/linked-list/194/747/nodelist.go new file mode 100644 index 0000000..c4c577f --- /dev/null +++ b/linked-list/194/747/nodelist.go @@ -0,0 +1,6 @@ +package rmendlist + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/194/747/rmendlist.go b/linked-list/194/747/rmendlist.go new file mode 100644 index 0000000..524ce58 --- /dev/null +++ b/linked-list/194/747/rmendlist.go @@ -0,0 +1,24 @@ +package rmendlist + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeNthFromEnd(head *ListNode, n int) *ListNode { + nrd, end := head, head + for i := 0; i < n; i++ { + end = end.Next + } + if end == nil { + return head.Next + } + for end.Next != nil { + nrd = nrd.Next + end = end.Next + } + nrd.Next = nrd.Next.Next + return head +} diff --git a/linked-list/194/747/rmendlist_test.go b/linked-list/194/747/rmendlist_test.go new file mode 100644 index 0000000..bba6572 --- /dev/null +++ b/linked-list/194/747/rmendlist_test.go @@ -0,0 +1,30 @@ +package rmendlist + +import "testing" + +func TestRmEndList(t *testing.T) { + head := &ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 3, + Next: &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 5, + }, + }, + }, + }, + } + + r := removeNthFromEnd(head, 2) + + re := []int{} + for r != nil { + re = append(re, r.Val) + r = r.Next + } + t.Log(re) +} diff --git a/linked-list/195/750/nodelist.go b/linked-list/195/750/nodelist.go new file mode 100644 index 0000000..cb0eece --- /dev/null +++ b/linked-list/195/750/nodelist.go @@ -0,0 +1,6 @@ +package reversesinglylist + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/195/750/reversesinglylist.go b/linked-list/195/750/reversesinglylist.go new file mode 100644 index 0000000..0ff85c9 --- /dev/null +++ b/linked-list/195/750/reversesinglylist.go @@ -0,0 +1,23 @@ +package reversesinglylist + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + firstnode, nextnode := head, head.Next + for nextnode != nil { + head.Next = nextnode.Next + nextnode.Next = firstnode + firstnode = nextnode + nextnode = head.Next + } + return firstnode +} diff --git a/linked-list/195/750/reversesinglylist_test.go b/linked-list/195/750/reversesinglylist_test.go new file mode 100644 index 0000000..3753e12 --- /dev/null +++ b/linked-list/195/750/reversesinglylist_test.go @@ -0,0 +1,30 @@ +package reversesinglylist + +import "testing" + +func TestReverseSinglyList(t *testing.T) { + head := &ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 3, + Next: &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 5, + }, + }, + }, + }, + } + + r := reverseList(head) + re := []int{} + for r != nil { + re = append(re, r.Val) + r = r.Next + } + + t.Log(re) +} diff --git a/linked-list/195/752/nodelist.go b/linked-list/195/752/nodelist.go new file mode 100644 index 0000000..8365285 --- /dev/null +++ b/linked-list/195/752/nodelist.go @@ -0,0 +1,6 @@ +package rmlistnode + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/195/752/rmlistnode.go b/linked-list/195/752/rmlistnode.go new file mode 100644 index 0000000..1a1f02f --- /dev/null +++ b/linked-list/195/752/rmlistnode.go @@ -0,0 +1,24 @@ +package rmlistnode + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeElements(head *ListNode, val int) *ListNode { + addnode := &ListNode{} + addnode.Next = head + + tmp := addnode + for tmp.Next != nil { + if tmp.Next.Val == val { + tmp.Next = tmp.Next.Next + continue + } + tmp = tmp.Next + } + + return addnode.Next +} diff --git a/linked-list/195/752/rmlistnode_test.go b/linked-list/195/752/rmlistnode_test.go new file mode 100644 index 0000000..5e93e79 --- /dev/null +++ b/linked-list/195/752/rmlistnode_test.go @@ -0,0 +1,25 @@ +package rmlistnode + +import "testing" + +func TestRmListNode(t *testing.T) { + val := 6 + sliceval := []int{1, 2, 6, 3, 4, 5, 6} + head := &ListNode{} + tmp := head + for i, v := range sliceval { + tmp.Val = v + if i == len(sliceval)-1 { + break + } + tmp.Next = &ListNode{} + tmp = tmp.Next + } + r := removeElements(head, val) + re := []int{} + for r != nil { + re = append(re, r.Val) + r = r.Next + } + t.Log(re) +} diff --git a/linked-list/195/753/listnode.go b/linked-list/195/753/listnode.go new file mode 100644 index 0000000..a48e9fa --- /dev/null +++ b/linked-list/195/753/listnode.go @@ -0,0 +1,6 @@ +package oddevenlist + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/195/753/oddevenlist.go b/linked-list/195/753/oddevenlist.go new file mode 100644 index 0000000..1dab7a4 --- /dev/null +++ b/linked-list/195/753/oddevenlist.go @@ -0,0 +1,26 @@ +package oddevenlist + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func oddEvenList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + odd, even := head, head.Next + tmp := even + for even != nil && even.Next != nil { + odd.Next = even.Next + odd = odd.Next + even.Next = odd.Next + even = even.Next + } + odd.Next = tmp + + return head +} diff --git a/linked-list/195/753/oddevenlist_test.go b/linked-list/195/753/oddevenlist_test.go new file mode 100644 index 0000000..dcd27f4 --- /dev/null +++ b/linked-list/195/753/oddevenlist_test.go @@ -0,0 +1,27 @@ +package oddevenlist + +import "testing" + +func TestOddEvenList(t *testing.T) { + head := &ListNode{} + val := []int{1, 2, 3, 4, 5} + + tmp := head + for i, v := range val { + tmp.Val = v + if i == len(val)-1 { + break + } + tmp.Next = &ListNode{} + tmp = tmp.Next + } + + r := oddEvenList(head) + re := []int{} + for r != nil { + re = append(re, r.Val) + r = r.Next + } + + t.Log(re) +} diff --git a/linked-list/195/754/listnode.go b/linked-list/195/754/listnode.go new file mode 100644 index 0000000..a9a09e3 --- /dev/null +++ b/linked-list/195/754/listnode.go @@ -0,0 +1,6 @@ +package palindromelist + +type ListNode struct { + Val int + Next *ListNode +} diff --git a/linked-list/195/754/palindromelist.go b/linked-list/195/754/palindromelist.go new file mode 100644 index 0000000..6c84f59 --- /dev/null +++ b/linked-list/195/754/palindromelist.go @@ -0,0 +1,54 @@ +package palindromelist + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func isPalindrome(head *ListNode) bool { + if head == nil || head.Next == nil { + return true + } + + midnode := middlenode(head) + midnode.Next = reverselist(midnode.Next) + + n1, n2 := head, midnode.Next + for n1 != nil && n2 != nil && n1.Val == n2.Val { + n1 = n1.Next + n2 = n2.Next + } + return n2 == nil +} + +// find middle of node in list +func middlenode(head *ListNode) *ListNode { + if head == nil { + return head + } + + slow, fast := head, head.Next + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + } + return slow +} + +// reverse list +func reverselist(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + var nl *ListNode + for head != nil { + tmp := head.Next + head.Next = nl + nl = head + head = tmp + } + return nl +} diff --git a/linked-list/195/754/palindromelist_test.go b/linked-list/195/754/palindromelist_test.go new file mode 100644 index 0000000..acb9672 --- /dev/null +++ b/linked-list/195/754/palindromelist_test.go @@ -0,0 +1,18 @@ +package palindromelist + +import "testing" + +func TestPalindromeList(t *testing.T) { + head := &ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + }, + } + + r := isPalindrome(head) + + if r { + t.Error("determine palindrome list error") + } +} diff --git a/linked-list/196/759/designdoublylist.go b/linked-list/196/759/designdoublylist.go new file mode 100644 index 0000000..05edc82 --- /dev/null +++ b/linked-list/196/759/designdoublylist.go @@ -0,0 +1,143 @@ +package designdoublylist + +type MyLinkedList struct { + size int + head *node + tail *node +} + +type node struct { + val int + prev *node + next *node +} + +/** Initialize your data structure here. */ +func Constructor() MyLinkedList { + return MyLinkedList{} +} + +/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ +func (this *MyLinkedList) Get(index int) int { + if index < 0 || index > this.size-1 { + return -1 + } + + tmp := this.head + for i := 0; i < index; i++ { + tmp = tmp.next + } + + return tmp.val +} + +/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ +func (this *MyLinkedList) AddAtHead(val int) { + tmp := &node{ + val: val, + } + + if this.size == 0 { + this.size++ + this.head = tmp + this.tail = tmp + return + } + + this.size++ + tmp.next = this.head + this.head.prev = tmp + this.head = tmp +} + +/** Append a node of value val to the last element of the linked list. */ +func (this *MyLinkedList) AddAtTail(val int) { + tmp := &node{ + val: val, + } + + if this.size == 0 { + this.size++ + this.head = tmp + this.tail = tmp + return + } + + this.size++ + tmp.prev = this.tail + this.tail.next = tmp + this.tail = tmp +} + +/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ +func (this *MyLinkedList) AddAtIndex(index int, val int) { + if index > this.size { + return + } + + if index == 0 { + this.AddAtHead(val) + return + } + + if index == this.size { + this.AddAtTail(val) + return + } + + this.size++ + + tmp := this.head + for i := 0; i < index; i++ { + tmp = tmp.next + } + + tmpnode := &node{ + val: val, + } + + tmpnode.next = tmp + tmpnode.prev = tmp.prev + tmp.prev.next = tmpnode + tmp.prev = tmpnode +} + +/** Delete the index-th node in the linked list, if the index is valid. */ +func (this *MyLinkedList) DeleteAtIndex(index int) { + if index > this.size-1 || this.size == 0 { + return + } + + if index == 0 { + this.size-- + this.head.next.prev = this.head.prev + this.head = this.head.next + return + } + + if index == this.size-1 { + this.size-- + this.tail.prev.next = this.tail.next + this.tail = this.tail.prev + return + } + + tmp := this.head + for i := 0; i < index; i++ { + tmp = tmp.next + } + + tmp.prev.next = tmp.next + tmp.next.prev = tmp.prev + this.size-- +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Get(index); + * obj.AddAtHead(val); + * obj.AddAtTail(val); + * obj.AddAtIndex(index,val); + * obj.DeleteAtIndex(index); + */ diff --git a/linked-list/196/759/designdoublylist_test.go b/linked-list/196/759/designdoublylist_test.go new file mode 100644 index 0000000..fe851c5 --- /dev/null +++ b/linked-list/196/759/designdoublylist_test.go @@ -0,0 +1,17 @@ +package designdoublylist + +import "testing" + +func TestDesignDoublyList(t *testing.T) { + dlist := Constructor() + dlist.AddAtHead(1) + dlist.AddAtTail(3) + dlist.AddAtIndex(1, 2) + r1 := dlist.Get(1) + dlist.DeleteAtIndex(1) + r2 := dlist.Get(1) + + if r1 != 2 || r2 != 3 { + t.Error("design doubly linked list error") + } +} diff --git a/queue-stack/216/865/queue.go b/queue-stack/216/865/queue.go new file mode 100644 index 0000000..814d7ef --- /dev/null +++ b/queue-stack/216/865/queue.go @@ -0,0 +1,107 @@ +package queue + +type MyCircularQueue struct { + head *node + tail *node + size int +} + +type node struct { + next *node + value interface{} +} + +/** Initialize your data structure here. Set the size of the queue to be k. */ +func Constructor(k int) MyCircularQueue { + return MyCircularQueue{ + size: k, + } +} + +/** Insert an element into the circular queue. Return true if the operation is successful. */ +func (this *MyCircularQueue) EnQueue(value int) bool { + if this.size == 0 { + return false + } else { + n := &node{ + value: value, + } + if this.tail == nil { + this.head = n + this.tail = n + this.size-- + } else { + this.tail.next = n + this.tail = n + this.size-- + } + return true + } +} + +/** Delete an element from the circular queue. Return true if the operation is successful. */ +func (this *MyCircularQueue) DeQueue() bool { + if this.head == nil { + return false + } else { + if this.head == this.tail { + this.head, this.tail = nil, nil + this.size++ + } else { + this.head = this.head.next + this.size++ + } + return true + } +} + +/** Get the front item from the queue. */ +func (this *MyCircularQueue) Front() int { + if this.head == nil { + return -1 + } + if v, ok := this.head.value.(int); ok { + return v + } else { + return -1 + } +} + +/** Get the last item from the queue. */ +func (this *MyCircularQueue) Rear() int { + if this.tail == nil { + return -1 + } + if v, ok := this.tail.value.(int); ok { + return v + } else { + return -1 + } +} + +/** Checks whether the circular queue is empty or not. */ +func (this *MyCircularQueue) IsEmpty() bool { + if (this.head == nil || this.tail == nil) && this.size != 0 { + return true + } + return false +} + +/** Checks whether the circular queue is full or not. */ +func (this *MyCircularQueue) IsFull() bool { + if this.head != nil && this.tail != nil && this.size == 0 { + return true + } + return false +} + +/** + * Your MyCircularQueue object will be instantiated and called as such: + * obj := Constructor(k); + * param_1 := obj.EnQueue(value); + * param_2 := obj.DeQueue(); + * param_3 := obj.Front(); + * param_4 := obj.Rear(); + * param_5 := obj.IsEmpty(); + * param_6 := obj.IsFull(); + */ diff --git a/queue-stack/216/865/queue_test.go b/queue-stack/216/865/queue_test.go new file mode 100644 index 0000000..95ac961 --- /dev/null +++ b/queue-stack/216/865/queue_test.go @@ -0,0 +1,53 @@ +package queue + +import "testing" + +func TestQueue(t *testing.T) { + //queue{nil, nil, 3} + queue := Constructor(3) + + //queue{&{nil, 1}, &{nil, 1}, 2} + if ok := queue.EnQueue(1); !ok { + t.Error("use value 1 enqueue error") + } + + //queue{&{&{nil, 2}, 1}, &{nil, 2}, 1} + if ok := queue.EnQueue(2); !ok { + t.Error("use value 2 enqueue error") + } + + //queue{&{&{&{nil, 3}, 2}, 1}, &{&{nil, 3}, 2}, &{nil, 3}, 0} + if ok := queue.EnQueue(3); !ok { + t.Error("use value 3 enqueue error") + } + + //queue{&{&{&{nil, 3}, 2}, 1}, &{&{nil, 3}, 2}, &{nil, 3}, 0} + if ok := queue.EnQueue(4); ok { + t.Error("queue isfull but enqueue success") + } + + //queue{&{&{&{nil, 3}, 2}, 1}, &{&{nil, 3}, 2}, &{nil, 3}, 0} + if queue.Rear() != 3 { + t.Error("get back of queue error") + } + + //queue{&{&{&{nil, 3}, 2}, 1}, &{&{nil, 3}, 2}, &{nil, 3}, 0} + if !queue.IsFull() { + t.Error("now queue isfull but not") + } + + //queue{&{&{nil, 3}, 2}, &{nil, 3}, 1} + if !queue.DeQueue() { + t.Error("dequeue error") + } + + //queue{&{&{&{nil, 4}, 3}, 2}, &{&{ni,4}, 3}, &{nil, 4}, 0} + if ok := queue.EnQueue(4); !ok { + t.Error("use value 4 enqueue error") + } + + //queue{&{&{&{nil, 4}, 3}, 2}, &{&{ni,4}, 3}, &{nil, 4}, 0} + if queue.Rear() != 4 { + t.Error("get back of queue error") + } +} diff --git a/queue-stack/217/872/lands.go b/queue-stack/217/872/lands.go new file mode 100644 index 0000000..ed3f578 --- /dev/null +++ b/queue-stack/217/872/lands.go @@ -0,0 +1,49 @@ +package lands + +import "container/list" + +func numIslands(grid [][]byte) int { + if grid == nil || len(grid) == 0 || len(grid[0]) == 0 { + return 0 + } + var islands int + for i := range grid { + for j := range grid[i] { + if grid[i][j] == '1' { + bfs(grid, i, j) + islands++ + } + } + } + return islands +} + +//bfs算法找到'1'以及周围的'1'并置'0' +func bfs(grid [][]byte, x int, y int) { + tmpx, tmpy := []int{0, 0, 1, -1}, []int{1, -1, 0, 0} + queue := list.New() + queue.PushBack(map[int]int{x: y}) + grid[x][y] = '0' + for queue.Len() > 0 { + q := queue.Front() + if m, ok := q.Value.(map[int]int); ok { + for k, v := range m { + for j := 0; j < 4; j++ { + if !inarea(grid, k+tmpx[j], v+tmpy[j]) { + continue + } + if grid[k+tmpx[j]][v+tmpy[j]] == '1' { + grid[k+tmpx[j]][v+tmpy[j]] = '0' + queue.PushBack(map[int]int{k + tmpx[j]: v + tmpy[j]}) + } + } + } + } + queue.Remove(q) + } +} + +func inarea(grid [][]byte, x int, y int) bool { + m, n := len(grid), len(grid[0]) + return x >= 0 && x < m && y >= 0 && y < n +} diff --git a/queue-stack/217/872/lands_test.go b/queue-stack/217/872/lands_test.go new file mode 100644 index 0000000..05b3124 --- /dev/null +++ b/queue-stack/217/872/lands_test.go @@ -0,0 +1,11 @@ +package lands + +import "testing" + +func TestNumIslands(t *testing.T) { + g := [][]byte{{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}} + r := numIslands(g) + if r != 1 { + t.Error("num of lands calculate error") + } +} diff --git a/queue-stack/217/873/lock.go b/queue-stack/217/873/lock.go new file mode 100644 index 0000000..3c0aa7b --- /dev/null +++ b/queue-stack/217/873/lock.go @@ -0,0 +1,88 @@ +package lock + +import "container/list" + +func openLock(deadends []string, target string) int { + for _, v := range deadends { + if v == "0000" { + return -1 + } + } + return bfs(deadends, target) +} + +func bfs(deadends []string, target string) int { + //初始化起始数字并转换为[]byte和需要返回的最小转换步数 + start, step := "0000", 0 + + //标记2种位变量 + tmp0, tmp9 := byte('0'-1), byte('9'+1) + + //记录已经访问的数字并记录start + used := map[string]bool{} + used[start] = true + + //开启队列并插入start + queue := list.New() + queue.PushBack(start) + + for queue.Len() > 0 { + l := queue.Len() + step++ + + for i := 0; i < l; i++ { + + v, ok := queue.Remove(queue.Front()).(string) + if !ok { + panic("get queue value error") + } + + tmpv := []byte(v) + addqueue9: + for ti := 0; ti < 4; ti++ { + tmpv[ti]++ + if tmpv[ti] == tmp9 { + tmpv[ti] = '0' + } + for _, s := range deadends { + if s == string(tmpv) { + tmpv[ti] = v[ti] + continue addqueue9 + } + } + if !used[string(tmpv)] { + queue.PushBack(string(tmpv)) + used[string(tmpv)] = true + } + if string(tmpv) == target { + return step + } + tmpv[ti] = v[ti] + } + + addqueue0: + for ti := 0; ti < 4; ti++ { + tmpv[ti]-- + if tmpv[ti] == tmp0 { + tmpv[ti] = '9' + } + for _, s := range deadends { + if s == string(tmpv) { + tmpv[ti] = v[ti] + continue addqueue0 + } + } + if !used[string(tmpv)] { + queue.PushBack(string(tmpv)) + used[string(tmpv)] = true + } + if string(tmpv) == target { + return step + } + tmpv[ti] = v[ti] + } + } + } + + return -1 +} diff --git a/queue-stack/217/873/lock_test.go b/queue-stack/217/873/lock_test.go new file mode 100644 index 0000000..bad94ea --- /dev/null +++ b/queue-stack/217/873/lock_test.go @@ -0,0 +1,13 @@ +package lock + +import ( + "testing" +) + +func TestLock(t *testing.T) { + dead, targ := []string{"0201", "0101", "0102", "1212", "2002"}, "0202" + r := openLock(dead, targ) + if r != 6 { + t.Error("openlock fail") + } +} diff --git a/queue-stack/217/874/square.go b/queue-stack/217/874/square.go new file mode 100644 index 0000000..77fbfe4 --- /dev/null +++ b/queue-stack/217/874/square.go @@ -0,0 +1,47 @@ +package square + +import "container/list" + +func numSquares(n int) int { + return bfs(n) +} + +func bfs(n int) int { + queue := list.New() + queue.PushBack(n) + + used := map[int]bool{} + used[n] = true + + var step int + + for queue.Len() > 0 { + l := queue.Len() + + step++ + + for i := 0; i < l; i++ { + + v, ok := queue.Remove(queue.Front()).(int) + if !ok { + panic("get queue value error") + } + + tmpi := 1 + tmpn := v - tmpi*tmpi + for tmpn >= 0 { + if tmpn == 0 { + return step + } + + if !used[tmpn] { + queue.PushBack(tmpn) + used[tmpn] = true + } + tmpi++ + tmpn = v - tmpi*tmpi + } + } + } + return step +} diff --git a/queue-stack/217/874/square_test.go b/queue-stack/217/874/square_test.go new file mode 100644 index 0000000..3b85ff5 --- /dev/null +++ b/queue-stack/217/874/square_test.go @@ -0,0 +1,13 @@ +package square + +import ( + "testing" +) + +func TestSquare(t *testing.T) { + n := 12 + r := numSquares(n) + if r != 3 { + t.Error("count error") + } +} diff --git a/queue-stack/218/877/minstack.go b/queue-stack/218/877/minstack.go new file mode 100644 index 0000000..2e74d46 --- /dev/null +++ b/queue-stack/218/877/minstack.go @@ -0,0 +1,43 @@ +package minstack + +type MinStack struct { + s []int +} + +/** initialize your data structure here. */ +func Constructor() MinStack { + return MinStack{ + s: []int{}, + } +} + +func (this *MinStack) Push(x int) { + this.s = append(this.s, x) +} + +func (this *MinStack) Pop() { + this.s = this.s[:len(this.s)-1] +} + +func (this *MinStack) Top() int { + return this.s[len(this.s)-1] +} + +func (this *MinStack) GetMin() int { + mini := this.s[0] + for _, v := range this.s { + if v < mini { + mini = v + } + } + return mini +} + +/** + * Your MinStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.GetMin(); + */ diff --git a/queue-stack/218/877/minstack_test.go b/queue-stack/218/877/minstack_test.go new file mode 100644 index 0000000..b0e7252 --- /dev/null +++ b/queue-stack/218/877/minstack_test.go @@ -0,0 +1,20 @@ +package minstack + +import "testing" + +func TestMinStack(t *testing.T) { + ms := Constructor() + ms.Push(-2) + ms.Push(0) + ms.Push(-3) + if mini1 := ms.GetMin(); mini1 != -3 { + t.Error("get mini value of stack error") + } + ms.Pop() + if tp := ms.Top(); tp != 0 { + t.Error("get top value of stack error") + } + if mini2 := ms.GetMin(); mini2 != -2 { + t.Error("get mini value of stack error") + } +} diff --git a/queue-stack/218/878/valid.go b/queue-stack/218/878/valid.go new file mode 100644 index 0000000..498c244 --- /dev/null +++ b/queue-stack/218/878/valid.go @@ -0,0 +1,41 @@ +package valid + +import "container/list" + +func isValid(s string) bool { + l := len(s) + + if l == 0 { + return true + } + + if l%2 != 0 { + return false + } + + stack := list.New() + for i := range s { + if s[i] == '(' || s[i] == '[' || s[i] == '{' { + stack.PushBack(s[i]) + } + + if s[i] == ')' || s[i] == ']' || s[i] == '}' { + if stack.Len() == 0 { + return false + } + v, ok := stack.Back().Value.(byte) + if !ok { + panic("get top of stack error") + } + if v+1 == s[i] || v+2 == s[i] { + stack.Remove(stack.Back()) + } + } + } + + if stack.Len() == 0 { + return true + } + + return false +} diff --git a/queue-stack/218/878/valid_test.go b/queue-stack/218/878/valid_test.go new file mode 100644 index 0000000..5d24733 --- /dev/null +++ b/queue-stack/218/878/valid_test.go @@ -0,0 +1,11 @@ +package valid + +import "testing" + +func TestValid(t *testing.T) { + s := "()" + r := isValid(s) + if !r { + t.Error("func isvalid error") + } +} diff --git a/queue-stack/218/879/temperature.go b/queue-stack/218/879/temperature.go new file mode 100644 index 0000000..a843283 --- /dev/null +++ b/queue-stack/218/879/temperature.go @@ -0,0 +1,25 @@ +package temperature + +import "container/list" + +func dailyTemperatures(T []int) []int { + l := len(T) + result := make([]int, l) + + stack := list.New() + for i := l - 1; i >= 0; i-- { + for stack.Len() != 0 && T[i] >= T[stack.Back().Value.(int)] { + stack.Remove(stack.Back()) + } + + if stack.Len() == 0 { + result[i] = 0 + } else { + result[i] = stack.Back().Value.(int) - i + } + + stack.PushBack(i) + } + + return result +} diff --git a/queue-stack/218/879/temperature_test.go b/queue-stack/218/879/temperature_test.go new file mode 100644 index 0000000..7b1b10c --- /dev/null +++ b/queue-stack/218/879/temperature_test.go @@ -0,0 +1,14 @@ +package temperature + +import "testing" + +func TestTemperature(t *testing.T) { + T := []int{73, 74, 75, 71, 69, 72, 76, 73} + result := []int{1, 1, 4, 2, 1, 1, 0, 0} + r := dailyTemperatures(T) + for i := 0; i < 8; i++ { + if r[i] != result[i] { + t.Error("func dailytemperatures return error") + } + } +} diff --git a/queue-stack/218/880/rpn.go b/queue-stack/218/880/rpn.go new file mode 100644 index 0000000..82fede7 --- /dev/null +++ b/queue-stack/218/880/rpn.go @@ -0,0 +1,50 @@ +package rpn + +import ( + "container/list" + "strconv" +) + +func evalRPN(tokens []string) int { + l := len(tokens) + var result int + + stack := list.New() + for i := 0; i < l; i++ { + if tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/" { + if v, err := strconv.Atoi(tokens[i]); err != nil { + panic(err) + } else { + stack.PushBack(v) + } + } + if tokens[i] == "+" { + t1 := stack.Remove(stack.Back()).(int) + t2 := stack.Remove(stack.Back()).(int) + t := t2 + t1 + stack.PushBack(t) + } + if tokens[i] == "-" { + t1 := stack.Remove(stack.Back()).(int) + t2 := stack.Remove(stack.Back()).(int) + t := t2 - t1 + stack.PushBack(t) + } + if tokens[i] == "*" { + t1 := stack.Remove(stack.Back()).(int) + t2 := stack.Remove(stack.Back()).(int) + t := t2 * t1 + stack.PushBack(t) + } + if tokens[i] == "/" { + t1 := stack.Remove(stack.Back()).(int) + t2 := stack.Remove(stack.Back()).(int) + t := t2 / t1 + stack.PushBack(t) + } + } + if stack.Len() == 1 { + result = stack.Remove(stack.Back()).(int) + } + return result +} diff --git a/queue-stack/218/880/rpn_test.go b/queue-stack/218/880/rpn_test.go new file mode 100644 index 0000000..a30d41a --- /dev/null +++ b/queue-stack/218/880/rpn_test.go @@ -0,0 +1,11 @@ +package rpn + +import "testing" + +func TestRpn(t *testing.T) { + tokens := []string{"2", "1", "+", "3", "*"} + r := evalRPN(tokens) + if r != 9 { + t.Error("rpn calculate error") + } +} diff --git a/queue-stack/219/883/lands.go b/queue-stack/219/883/lands.go new file mode 100644 index 0000000..df38574 --- /dev/null +++ b/queue-stack/219/883/lands.go @@ -0,0 +1,47 @@ +package lands + +func numIslands(grid [][]byte) int { + var count int + + if grid == nil || len(grid) == 0 || len(grid[0]) == 0 { + return 0 + } + + for i := range grid { + for j := range grid[i] { + if grid[i][j] == '1' { + dfs(grid, i, j) + count++ + } + } + } + return count +} + +//dfs深度函数将'1'置'0' +func dfs(grid [][]byte, x int, y int) { + lx, ly := len(grid), len(grid[0]) + + if x >= lx || y >= ly { + return + } + + if grid[x][y] == '0' { + return + } + + grid[x][y] = '0' + + if x < lx { + dfs(grid, x+1, y) + } + if x > 0 { + dfs(grid, x-1, y) + } + if y < ly { + dfs(grid, x, y+1) + } + if y > 0 { + dfs(grid, x, y-1) + } +} diff --git a/queue-stack/219/883/lands_test.go b/queue-stack/219/883/lands_test.go new file mode 100644 index 0000000..05b3124 --- /dev/null +++ b/queue-stack/219/883/lands_test.go @@ -0,0 +1,11 @@ +package lands + +import "testing" + +func TestNumIslands(t *testing.T) { + g := [][]byte{{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}} + r := numIslands(g) + if r != 1 { + t.Error("num of lands calculate error") + } +} diff --git a/queue-stack/219/884/clonegraph.go b/queue-stack/219/884/clonegraph.go new file mode 100644 index 0000000..311260b --- /dev/null +++ b/queue-stack/219/884/clonegraph.go @@ -0,0 +1 @@ +package clonegraph diff --git a/queue-stack/219/884/clonegraph_test.go b/queue-stack/219/884/clonegraph_test.go new file mode 100644 index 0000000..311260b --- /dev/null +++ b/queue-stack/219/884/clonegraph_test.go @@ -0,0 +1 @@ +package clonegraph diff --git a/queue-stack/219/885/targetsum.go b/queue-stack/219/885/targetsum.go new file mode 100644 index 0000000..1333f4f --- /dev/null +++ b/queue-stack/219/885/targetsum.go @@ -0,0 +1,23 @@ +package targetsum + +func findTargetSumWays(nums []int, S int) int { + l := len(nums) + + count := new(int) + *count = 0 + + dfs(nums, S, 0, l, count) + return *count +} + +func dfs(nums []int, S int, start int, lnums int, count *int) { + if start >= lnums { + if S == 0 { + *count++ + } + return + } + + dfs(nums, S-nums[start], start+1, lnums, count) + dfs(nums, S+nums[start], start+1, lnums, count) +} diff --git a/queue-stack/219/885/targetsum_test.go b/queue-stack/219/885/targetsum_test.go new file mode 100644 index 0000000..e1478ce --- /dev/null +++ b/queue-stack/219/885/targetsum_test.go @@ -0,0 +1,11 @@ +package targetsum + +import "testing" + +func TestTargetsum(t *testing.T) { + nums, S := []int{1, 1, 1, 1, 1}, 3 + r := findTargetSumWays(nums, S) + if r != 5 { + t.Error("func findtargetsumways count error") + } +} diff --git a/queue-stack/219/887/binarytree.go b/queue-stack/219/887/binarytree.go new file mode 100644 index 0000000..14623a1 --- /dev/null +++ b/queue-stack/219/887/binarytree.go @@ -0,0 +1,38 @@ +package binarytree + +import "container/list" + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func inorderTraversal(root *TreeNode) []int { + + return dfs(root) +} + +func dfs(root *TreeNode) []int { + result := []int{} + + stack, node := list.New(), root + + for node != nil || stack.Len() > 0 { + for node != nil { + stack.PushBack(node) + node = node.Left + } + + if stack.Len() > 0 { + tmp := stack.Back().Value.(*TreeNode) + stack.Remove(stack.Back()) + result = append(result, tmp.Val) + node = tmp.Right + } + } + + return result +} diff --git a/queue-stack/219/887/binarytree_test.go b/queue-stack/219/887/binarytree_test.go new file mode 100644 index 0000000..1f1b06a --- /dev/null +++ b/queue-stack/219/887/binarytree_test.go @@ -0,0 +1,27 @@ +package binarytree + +import ( + "testing" +) + +func TestBinarytree(t *testing.T) { + //[1,null,2,3] + root := &TreeNode{ + Val: 1, + } + root.Right = &TreeNode{ + Val: 2, + } + root.Right.Left = &TreeNode{ + Val: 3, + } + expectation := []int{1, 3, 2} + + r := inorderTraversal(root) + + for i, v := range r { + if v != expectation[i] { + t.Error("traversal binarytree error") + } + } +} diff --git a/queue-stack/219/887/treenode.go b/queue-stack/219/887/treenode.go new file mode 100644 index 0000000..e201282 --- /dev/null +++ b/queue-stack/219/887/treenode.go @@ -0,0 +1,7 @@ +package binarytree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} diff --git a/queue-stack/220/888/stackTqueue.go b/queue-stack/220/888/stackTqueue.go new file mode 100644 index 0000000..3368e50 --- /dev/null +++ b/queue-stack/220/888/stackTqueue.go @@ -0,0 +1,60 @@ +package stackTqueue + +import "container/list" + +type MyQueue struct { + store *list.List + search *list.List +} + +/** Initialize your data structure here. */ +func Constructor() MyQueue { + return MyQueue{ + store: list.New(), + search: list.New(), + } +} + +/** Push element x to the back of queue. */ +func (this *MyQueue) Push(x int) { + this.store.PushBack(x) +} + +/** Removes the element from in front of queue and returns that element. */ +func (this *MyQueue) Pop() int { + if this.search.Len() == 0 { + storeTsearch(this.store, this.search) + } + return this.search.Remove(this.search.Back()).(int) +} + +/** Get the front element. */ +func (this *MyQueue) Peek() int { + if this.search.Len() == 0 { + storeTsearch(this.store, this.search) + } + return this.search.Back().Value.(int) +} + +/** Returns whether the queue is empty. */ +func (this *MyQueue) Empty() bool { + if this.store.Len() == 0 && this.search.Len() == 0 { + return true + } + return false +} + +func storeTsearch(store *list.List, search *list.List) { + for store.Len() > 0 { + search.PushBack(store.Remove(store.Back())) + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * param_2 := obj.Pop(); + * param_3 := obj.Peek(); + * param_4 := obj.Empty(); + */ diff --git a/queue-stack/220/888/stackTqueue_test.go b/queue-stack/220/888/stackTqueue_test.go new file mode 100644 index 0000000..a65d398 --- /dev/null +++ b/queue-stack/220/888/stackTqueue_test.go @@ -0,0 +1,18 @@ +package stackTqueue + +import "testing" + +func TestStackToQueue(t *testing.T) { + q := Constructor() + q.Push(1) + q.Push(2) + if r := q.Peek(); r != 1 { + t.Error("queue get font element error") + } + if r := q.Pop(); r != 1 { + t.Error("queue remove font element error") + } + if q.Empty() { + t.Error("queue has one element but empty error") + } +} diff --git a/queue-stack/220/889/queueTstack.go b/queue-stack/220/889/queueTstack.go new file mode 100644 index 0000000..2cf24aa --- /dev/null +++ b/queue-stack/220/889/queueTstack.go @@ -0,0 +1,72 @@ +package queueTstack + +import "container/list" + +type MyStack struct { + queue0 *list.List + queue1 *list.List +} + +/** Initialize your data structure here. */ +func Constructor() MyStack { + return MyStack{ + queue0: list.New(), + queue1: list.New(), + } +} + +/** Push element x onto stack. */ +func (this *MyStack) Push(x int) { + if this.queue0.Len() == 0 && this.queue1.Len() == 0 { + this.queue0.PushBack(x) + return + } + if this.queue0.Len() > 0 { + this.queue0.PushBack(x) + return + } + if this.queue1.Len() > 0 { + this.queue1.PushBack(x) + return + } +} + +/** Removes the element on top of the stack and returns that element. */ +func (this *MyStack) Pop() int { + if this.queue0.Len() > 0 { + queueTbrothers(this.queue0, this.queue1) + return this.queue0.Remove(this.queue0.Front()).(int) + } + queueTbrothers(this.queue1, this.queue0) + return this.queue1.Remove(this.queue1.Front()).(int) +} + +/** Get the top element. */ +func (this *MyStack) Top() int { + tmp := this.Pop() + this.Push(tmp) + return tmp +} + +/** Returns whether the stack is empty. */ +func (this *MyStack) Empty() bool { + return this.queue0.Len() == 0 && this.queue1.Len() == 0 +} + +func queueTbrothers(start *list.List, end *list.List) { + for start.Len() > 0 { + if start.Len() == 1 { + break + } + end.PushBack(start.Remove(start.Front())) + } +} + +/** + * Your MyStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * param_2 := obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.Empty(); + */ diff --git a/queue-stack/220/889/queueTstack_test.go b/queue-stack/220/889/queueTstack_test.go new file mode 100644 index 0000000..da1b87c --- /dev/null +++ b/queue-stack/220/889/queueTstack_test.go @@ -0,0 +1,18 @@ +package queueTstack + +import "testing" + +func TestStackToQueue(t *testing.T) { + stack := Constructor() + stack.Push(1) + stack.Push(2) + if r := stack.Top(); r != 2 { + t.Error("get top of stack error") + } + if r := stack.Pop(); r != 2 { + t.Error("remove top of stack error") + } + if stack.Empty() { + t.Error("stack has one element but empty error") + } +} diff --git a/queue-stack/220/890/decodestring.go b/queue-stack/220/890/decodestring.go new file mode 100644 index 0000000..c7d2007 --- /dev/null +++ b/queue-stack/220/890/decodestring.go @@ -0,0 +1,37 @@ +package decodestring + +import "container/list" + +func decodeString(s string) string { + l := len(s) + var result string + + countstack, stringstack := list.New(), list.New() + + var count int + for i := 0; i < l; i++ { + if s[i] > 47 && s[i] < 58 { + + count = count*10 + int(s[i]-'0') + + } else if s[i] == '[' { + + countstack.PushBack(count) + stringstack.PushBack(result) + + count = 0 + result = "" + } else if s[i] == ']' { + tmpcount := countstack.Remove(countstack.Back()).(int) + tmpstring := stringstack.Remove(stringstack.Back()).(string) + for j := 0; j < tmpcount; j++ { + tmpstring += result + } + result = tmpstring + } else { + result += string(s[i]) + } + } + + return result +} diff --git a/queue-stack/220/890/decodestring_test.go b/queue-stack/220/890/decodestring_test.go new file mode 100644 index 0000000..bc47655 --- /dev/null +++ b/queue-stack/220/890/decodestring_test.go @@ -0,0 +1,11 @@ +package decodestring + +import "testing" + +func TestDecodestring(t *testing.T) { + s := "3[a2[c]]" + r := decodeString(s) + if r != "accaccacc" { + t.Error("decode string error") + } +} diff --git a/queue-stack/220/891/floodfill.go b/queue-stack/220/891/floodfill.go new file mode 100644 index 0000000..80a06aa --- /dev/null +++ b/queue-stack/220/891/floodfill.go @@ -0,0 +1,50 @@ +package floodfill + +func floodFill(image [][]int, sr int, sc int, newColor int) [][]int { + lx, ly := len(image), len(image[0]) + if lx == 0 || lx > 50 { + panic("image too short or too long") + } + if ly == 0 || ly > 50 { + panic("image[0] too short or too long") + } + if sr < 0 || sr >= lx { + panic("sr not in range") + } + if sc < 0 || sc >= ly { + panic("sc not in range") + } + if newColor < 0 || newColor > 65535 { + panic("newColor not in range") + } + oldColor := image[sr][sc] + if newColor == oldColor { + return image + } + + dfs(image, sr, sc, newColor, oldColor) + return image +} + +func dfs(image [][]int, sr int, sc int, newColor int, oldColor int) { + lx, ly := len(image), len(image[0]) + + if image[sr][sc] != oldColor { + return + } + + image[sr][sc] = newColor + + if sr > 0 { + dfs(image, sr-1, sc, newColor, oldColor) + } + if sr < lx-1 { + dfs(image, sr+1, sc, newColor, oldColor) + } + if sc > 0 { + dfs(image, sr, sc-1, newColor, oldColor) + } + if sc < ly-1 { + dfs(image, sr, sc+1, newColor, oldColor) + } +} diff --git a/queue-stack/220/891/floodfill_test.go b/queue-stack/220/891/floodfill_test.go new file mode 100644 index 0000000..cbc955d --- /dev/null +++ b/queue-stack/220/891/floodfill_test.go @@ -0,0 +1,18 @@ +package floodfill + +import "testing" + +func TestFloodFill(t *testing.T) { + image := [][]int{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}} + sr, sc, newColor := 1, 1, 2 + expection := [][]int{{2, 2, 2}, {2, 2, 0}, {2, 0, 1}} + + r := floodFill(image, sr, sc, newColor) + for ri := range r { + for rj := range r[ri] { + if r[ri][rj] != expection[ri][rj] { + t.Error("func floodFill error") + } + } + } +} diff --git a/queue-stack/220/892/matrix.go b/queue-stack/220/892/matrix.go new file mode 100644 index 0000000..8ade77b --- /dev/null +++ b/queue-stack/220/892/matrix.go @@ -0,0 +1,129 @@ +package matrix + +import "container/list" + +func updateMatrix(matrix [][]int) [][]int { + if len(matrix) == 0 || len(matrix[0]) == 0 { + panic("matrix is empty") + } + + for i := range matrix { + for j := range matrix[i] { + if matrix[i][j] == 1 { + bfs(matrix, i, j) + } + } + } + + return matrix +} + +func bfs(matrix [][]int, x int, y int) { + lx, ly := len(matrix), len(matrix[0]) + + var step int + + queue, used := list.New(), map[point]bool{} + + queue.PushBack(point{ + x: x, + y: y, + }) + used[point{ + x: x, + y: y, + }] = true + +start: + for queue.Len() > 0 { + + ql := queue.Len() + step++ + + for i := 0; i < ql; i++ { + pv := queue.Remove(queue.Front()).(point) + + if pv.x+1 < lx { + if matrix[pv.x+1][pv.y] != 0 && !used[point{ + x: pv.x + 1, + y: pv.y, + }] { + queue.PushBack(point{ + x: pv.x + 1, + y: pv.y, + }) + used[point{ + x: pv.x + 1, + y: pv.y, + }] = true + } + if matrix[pv.x+1][pv.y] == 0 { + matrix[x][y] = step + break start + } + } + if pv.x-1 >= 0 { + if matrix[pv.x-1][pv.y] != 0 && !used[point{ + x: pv.x - 1, + y: pv.y, + }] { + queue.PushBack(point{ + x: pv.x - 1, + y: pv.y, + }) + used[point{ + x: pv.x - 1, + y: pv.y, + }] = true + } + if matrix[pv.x-1][pv.y] == 0 { + matrix[x][y] = step + break start + } + } + if pv.y+1 < ly { + if matrix[pv.x][pv.y+1] != 0 && !used[point{ + x: pv.x, + y: pv.y + 1, + }] { + queue.PushBack(point{ + x: pv.x, + y: pv.y + 1, + }) + used[point{ + x: pv.x, + y: pv.y + 1, + }] = true + } + if matrix[pv.x][pv.y+1] == 0 { + matrix[x][y] = step + break start + } + } + if pv.y-1 >= 0 { + if matrix[pv.x][pv.y-1] != 0 && !used[point{ + x: pv.x, + y: pv.y - 1, + }] { + queue.PushBack(point{ + x: pv.x, + y: pv.y - 1, + }) + used[point{ + x: pv.x, + y: pv.y - 1, + }] = true + } + if matrix[pv.x][pv.y-1] == 0 { + matrix[x][y] = step + break start + } + } + } + } +} + +type point struct { + x int + y int +} diff --git a/queue-stack/220/892/matrix_test.go b/queue-stack/220/892/matrix_test.go new file mode 100644 index 0000000..af26dd1 --- /dev/null +++ b/queue-stack/220/892/matrix_test.go @@ -0,0 +1,23 @@ +package matrix + +import "testing" + +func TestMatrix(t *testing.T) { + + matrix := [][]int{ + {0, 0, 0}, + {0, 1, 0}, + {0, 0, 0}, + } + r := updateMatrix(matrix) + expectation := matrix + + for i := range r { + for j := range r[i] { + if expectation[i][j] != r[i][j] { + t.Error("update matrix error") + } + } + } + +} diff --git a/queue-stack/220/893/keysArooms.go b/queue-stack/220/893/keysArooms.go new file mode 100644 index 0000000..934cdf7 --- /dev/null +++ b/queue-stack/220/893/keysArooms.go @@ -0,0 +1,19 @@ +package keysArooms + +func canVisitAllRooms(rooms [][]int) bool { + + visited := map[int]bool{} + + dfs(rooms, 0, visited) + + return len(rooms) == len(visited) +} + +func dfs(rooms [][]int, keys int, visited map[int]bool) { + if !visited[keys] { + visited[keys] = true + for i := range rooms[keys] { + dfs(rooms, rooms[keys][i], visited) + } + } +} diff --git a/queue-stack/220/893/keysArooms_test.go b/queue-stack/220/893/keysArooms_test.go new file mode 100644 index 0000000..8ef2c2d --- /dev/null +++ b/queue-stack/220/893/keysArooms_test.go @@ -0,0 +1,18 @@ +package keysArooms + +import "testing" + +func TestKeysAndRooms(t *testing.T) { + rooms := [][]int{ + {1}, + {2}, + {3}, + {}, + } + + r := canVisitAllRooms(rooms) + + if !r { + t.Error("visit room error") + } +}