Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a new medium question and solution #12

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Solutions/Solutions/Medium/Medium_099_Number_Of_Islands.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
https://leetcode.com/problems/number-of-islands/
#99 Number Of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
*/
import UIKit
class Medium_099_Number_Of_Islands{
func numIslands(_ grid: [[Character]]) -> Int {
guard grid.count > 0 else { return 0 }
guard grid[0].count > 0 else { return 0 }
var grid = grid
var islandCounter = 0
for i in 0..<grid.count{
for j in 0..<grid[i].count{
if grid[i][j] == "1"{
islandCounter += 1
LandSink(&grid, i, j)
}
}
}
return islandCounter
}
func LandSink(_ grid : inout [[Character]], _ i : Int, _ j : Int){
if i >= 0 && j >= 0 && i < grid.count && j < grid[i].count && grid[i][j] == "1" {
grid[i][j] = "0"
LandSink(&grid, i+1, j)
LandSink(&grid, i-1, j)
LandSink(&grid, i, j+1)
LandSink(&grid, i, j-1)
}
else{
return
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//
// Medium_099_Number_Of_Islands_Test.swift
// Medium_099_Number_Of_IslandsTests
//
// Copyright © 2020 Jayant Sogiakar. All rights reserved.
//

import Foundation
import XCTest
@testable import Medium_099_Number_Of_Islands
class Medium_099_Number_Of_Islands_Test: XCTestCase {
func test_001(){
let val = numIslands([
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
])
XCTAssertEqual(val, 1)
}
func test_002(){
let val = numIslands([
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
])
XCTAssertEqual(val, 3)
}
func test_3(){
let val = numIslands( [["1","0","1","1","0","1","1"]])
XCTAssertEqual(val, 3)
}
}