lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

N = lines[0][0]
M = lines[0][1]

access = []
for i in 1..N do
  access[i-1] = []
end
for i in 1..M do
  from = lines[i][0]
  to = lines[i][1]
  access[to-1].push(from)
  access[from-1].push(to)
end

visited = []
for i in 1..N do
  visited[i-1] = false
end

num_group = 0
for i in 1..N do
  if visited[i-1] == false then
    num_group += 1
    targets = [i]
    while targets != [] do
      j = targets.pop
      visited[j-1] = true
      access[j-1].each do |k|
        if visited[k-1] == false then
          targets.push(k)
          visited[k-1] = true
        end
      end
    end
  end
end
    
puts num_group - 1